Long Polling is a polling technique that keeps connections open for an extended period, facilitating instant response when server updates become available. Its implementation can be quite straightforward.
To serve requests using Apache, create a PHP script like msgsrv.php. Here's a simple example:
// Simulate data availability after a random delay sleep(rand(2, 10)); echo("Hi! Here's a random number: " . rand(1, 10));
Run this script on Apache. Note that using a high-volume webserver like Apache may result in exhausted worker threads.
In JavaScript, you can use a script like long_poller.htm to initiate polling requests:
<script> function waitForMsg() { $.ajax({ type: "GET", url: "msgsrv.php", async: true, cache: false, timeout: 50000, success: function(data) { // Append the response to a div addmsg("new", data); // Continue polling after 1 second setTimeout(waitForMsg, 1000); }, error: function(..., errorThrown) { // Append error to div addmsg("error", textStatus + " (" + errorThrown + ")"); // Retry after 15 seconds setTimeout(waitForMsg, 15000); } }); } $(document).ready(function() { waitForMsg(); // Start the initial request }); </script>
This script continuously makes requests to msgsrv.php, displaying responses in a div. It uses a simple rate limiter to prevent excessive requests.
Long Polling offers resilience and simplicity. In case of network interruptions, the client retries automatically. It's a suitable choice for applications requiring immediate updates from the server, such as instant messaging or chat applications.
The above is the detailed content of How to Implement Basic Long Polling Using Apache and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!