Implementing Basic Long Polling: A Simple Guide
Long polling is a technique used to enable the server to push data to the client without the client explicitly requesting it. This is useful in scenarios where the server needs to continuously monitor data and notify the client when new data arrives.
How does Long Polling work?
In long polling, the client makes a request to the server and waits for a response. If no data is available, the server keeps the request open indefinitely, instead of closing it like in a regular HTTP request. When new data becomes available, the server sends it to the client and closes the request.
Implementing Long Polling in Apache and PHP
To implement long polling using Apache and PHP:
Client-side Implementation using Javascript
To implement long polling on the client side using Javascript:
Example Code
PHP Script (msgsrv.php):
if (rand(1, 3) == 1) { // Fake an error header("HTTP/1.0 404 Not Found"); die(); } // Send a string after a random number of seconds (2-10) sleep(rand(2, 10)); echo("Hi! Have a random number: " . rand(1, 10));
Javascript Code (long_poller.htm):
<script type="text/javascript"> function waitForMsg() { $.ajax({ type: "GET", url: "msgsrv.php", async: true, cache: false, timeout: 50000, success: function (data) { // Add response to a .msg div (with the "new" class) addmsg("new", data); setTimeout(waitForMsg, 1000); // Request next message after 1 second }, error: function (XMLHttpRequest, textStatus, errorThrown) { // Add error message addmsg("error", textStatus + " (" + errorThrown + ")"); setTimeout(waitForMsg, 15000); // Retry after 15 seconds } }); }; $(document).ready(function () { waitForMsg(); // Start the initial request }); </script>
The above is the detailed content of How Does Long Polling Work and How Can It Be Implemented Using Apache, PHP, and Javascript?. For more information, please follow other related articles on the PHP Chinese website!