Home > Backend Development > PHP Tutorial > How to Implement Basic Long Polling Using Apache and JavaScript?

How to Implement Basic Long Polling Using Apache and JavaScript?

Linda Hamilton
Release: 2024-12-30 12:16:13
Original
882 people have browsed it

How to Implement Basic Long Polling Using Apache and JavaScript?

Achieving Basic Long Polling Implementation

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.

Apache as a Request Handler

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));
Copy after login

Run this script on Apache. Note that using a high-volume webserver like Apache may result in exhausted worker threads.

Using a JavaScript Script

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>
Copy after login

This script continuously makes requests to msgsrv.php, displaying responses in a div. It uses a simple rate limiter to prevent excessive requests.

Benefits of Long Polling

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template