Home >Backend Development >PHP Tutorial >How to Implement Simple Long Polling Using Apache and PHP?
Implementing Simple Long Polling
Many resources describe the concept of long polling, but practical implementation examples remain elusive. Let's delve into a simplified version without relying on complex frameworks or server configurations.
Using Apache and PHP for Server Communication
To handle server requests, Apache is adequate. The PHP script below sends a random string after a random interval, simulating real-time message arrival. Occasionally, it returns an error for demonstration purposes.
<?php if (rand(1, 3) == 1) { header("HTTP/1.0 404 Not Found"); die(); } sleep(rand(2, 10)); echo("Hi! Have a random number: " . rand(1, 10)); ?>
JavaScript Client for Long Polling
In JavaScript, the long poller continually requests the above script and waits for a response:
<script type="text/javascript"> function waitForMsg() { $.ajax({ type: "GET", url: "msgsrv.php", success: function(data) { // Display the message $("#messages").append("<div class='msg new'>" + data + "</div>"); // Recursively invoke waitForMsg setTimeout(waitForMsg, 1000); }, error: function() { // Display the error message and restart the process after 15 seconds $("#messages").append("<div class='msg error'>Error encountered</div>"); setTimeout(waitForMsg, 15000); } }); } $(document).ready(function() { waitForMsg(); }); </script>
This script continuously checks for server updates and displays incoming messages. Error handling is incorporated, and the long poller attempts to reconnect after a specified timeout period.
Strengths of Long Polling
Long polling offers several benefits:
The above is the detailed content of How to Implement Simple Long Polling Using Apache and PHP?. For more information, please follow other related articles on the PHP Chinese website!