Take the 2-minute tour ×

I can find lots of information on how Long Polling works (For example, this, and this), but no simple examples of how to implement this in code.

All I can find is cometd, which relies on the Dojo JS framework, and a fairly complex server system..

Basically, how would I use Apache to serve the requests, and how would I write a simple script (say, in PHP) which would "long-poll" the server for new messages?

The example doesn't have to be scaleable, secure or complete, it just needs to work!

share|improve this question
Note: I know apache isn't suited to serving long-poll requests, as you'd quickly run out of threads on the server (thus mentioning the example doesn't need to scale).. I just need something generic and simple, to understand the basic implementation.. Thanks! –  dbr Dec 2 '08 at 11:16
Extremely simple client & server demo in this repo: php-long-polling –  Panique Nov 21 '13 at 1:46
add comment

17 Answers

up vote 359 down vote accepted

It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).

Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)


if(rand(1,3) == 1){
    /* Fake an error */
    header("HTTP/1.0 404 Not Found");

/* Send a string after a random number of seconds (2-10) */
echo("Hi! Have a random number: " . rand(1,10));

Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)

Then, in Javascript, you request the above file (msg_srv.php), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)

What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php file.. If it succeeds, we append the message to the #messages div, then after 1 second we call the waitForMsg function again, which triggers the wait.

The 1 second setTimeout() is a really basic rate-limiter, it works fine without this, but if msgsrv.php always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.

If the page errors, it appends the error to the #messages div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)

The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required

Anyway, the long_poller.htm code, using the jQuery framework:


      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}

    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
            "<div class='msg "+ type +"'>"+ msg +"</div>"

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
            type: "GET",
            url: "msgsrv.php",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */

        waitForMsg(); /* Start the inital request */
    <div id="messages">
        <div class="msg old">
            BargePoll message requester!
share|improve this answer
Couldn't some messages slip through using this idea? In that 1 second time out, say 1000 chat messages were sent, how would the server know to send the 1000 messsages specifically to that client? –  DevDevDev Oct 7 '09 at 3:36
Probably. This is a very simplified example, to demonstrate the concept.. To do this better you'd need more elaborate server-side code, where it would store up those 1000 messages for that specific client, and send them in one chunk. You could also safely reduce the waitForMsg timeout –  dbr Oct 7 '09 at 13:32
nodejs is another excellent server side solution for long polling requests, with the additional advantage (over Twisted) that you can write server code in Javascript too. –  Husky Feb 25 '11 at 19:10
the question is what does a real PHP script do instead of sleep(rand(2,10)); ? in order to do nothing, poll the database each 100 milisecs? when does it decide to die? –  Luis Siquot Sep 28 '11 at 3:29
You don't need to wait 1 second for resending the long-polling request to the server, even if it responds instantly. Be sure to test it very throughly when using in production because it leads to very delicate technical considerations, both client-side and server-side. @LuisSiquot - A real example in PHP is using a do...while loop querying the database for new "events" on a very-much-indexed database table, for example and breaking the loop when there are. You MUST do a usleep(250000) to sleep 250ms and unload the CPU. More info: zeitoun.net/articles/comet_and_php/start –  Alejandro Iglesias May 11 '12 at 20:47
show 15 more comments

I've got a really simple chat example as part of slosh.

Edit: (since everyone's pasting their code in here)

This is the complete JSON-based multi-user chat using long-polling and slosh. This is a demo of how to do the calls, so please ignore the XSS problems. Nobody should deploy this without sanitizing it first.

Notice that the client always has a connection to the server, and as soon as anyone sends a message, everyone should see it roughly instantly.

<!-- Copyright (c) 2008 Dustin Sallings <dustin+html@spy.net> -->
<html lang="en">
    <title>slosh chat</title>
    <script type="text/javascript"
    <link title="Default" rel="stylesheet" media="screen" href="style.css" />

    <h1>Welcome to Slosh Chat</h1>

    <div id="messages">
        <span class="from">First!:</span>
        <span class="msg">Welcome to chat. Please don't hurt each other.</span>

      <div>Nick: <input id='from' type="text" name="from"/></div>
      <div><textarea id='msg' name="msg"></textarea></div>
      <div><input type="submit" value="Say it" id="submit"/></div>

    <script type="text/javascript">
      function gotData(json, st) {
        var msgs=$('#messages');
        $.each(json.res, function(idx, p) {
          var from = p.from[0]
          var msg = p.msg[0]
          msgs.append("<div><span class='from'>" + from + ":</span>" +
            " <span class='msg'>" + msg + "</span></div>");
        // The jQuery wrapped msgs above does not work here.
        var msgs=document.getElementById("messages");
        msgs.scrollTop = msgs.scrollHeight;

      function getNewComments() {
        $.getJSON('/topics/chat.json', gotData);

      $(document).ready(function() {
          $.post('/topics/chat', $('form').serialize());
          return false;
share|improve this answer
May I know how this is always connected ? Sorry if I am asking something silly, but I want to know that. –  Rocky Singh Jan 22 '11 at 23:31
It does an HTTP GET and the server blocks the GET until there's data available. When data arrives to the server, the server returns the data to the client, queues whatever else might be coming in and then the client reconnects and picks up the missing messages if any, otherwise it blocks again. –  Dustin Jan 22 '11 at 23:46
add comment

Tornado is designed for long-polling, and includes a very minimal (few hundred lines of Python) chat app in /examples/chatdemo , including server code and JS client code. It works like this:

  • Clients use JS to ask for an updates since (number of last message), server URLHandler receives these and adds a callback to respond to the client to a queue.

  • When the server gets a new message, the onmessage event fires, loops through the callbacks, and sends the messages.

  • The client-side JS receives the message, adds it to the page, then asks for updates since this new message ID.

share|improve this answer
add comment

I think the client looks like a normal asynchronous AJAX request, but you expect it to take a "long time" to come back.

The server then looks like this.

while (!hasNewData())


So, the AJAX request goes to the server, probably including a timestamp of when it was last update so that your hasNewData() knows what data you have already got. The server then sits in a loop sleeping until new data is available. All the while, your AJAX request is still connected, just hanging there waiting for data. Finally, when new data is available, the server gives it to your AJAX request and closes the connection.

share|improve this answer
This is a busy wait that blocks your current thread. That doesn't scale at all. –  Wouter Lievens Sep 24 '09 at 9:41
No, usleep is not a busy wait. And the whole point of "waiting" is to block your thread for a while. Probably he meant 50 milliseconds (usleep(50000)) though, not 50 microseconds! But anyway, with a typical Apache/PHP setup, is there any other way to do this? –  Matt Nov 27 '11 at 20:30
@Matt not with apache –  Alejandro Iglesias May 11 '12 at 20:52
Well, from the priciple, you cannot make a blocking function for chat message without wait. –  Tomáš Zato Nov 26 '13 at 20:06
add comment

This is a nice 5-minute screencast on how to do long polling using PHP & jQuery: http://screenr.com/SNH

Code is quite similar to dbr's example above.

share|improve this answer
I think you should only see this as an introduction to long-polling because this implementation will for sure kill your server with many concurrent users. –  Alfred Feb 22 '10 at 17:58
im just learning about all this...how dependable, or not, is it with a few users...say 10 chatting back n forth? –  somdow Apr 4 '12 at 14:12
add comment

Here are some classes I use for long-polling in C#. There are basically 6 classes (see below).

  1. Controller: Processes actions required to create a valid response (db operations etc.)
  2. Processor: Manages asynch communication with the web page (itself)
  3. IAsynchProcessor: The service processes instances that implement this interface
  4. Sevice: Processes request objects that implement IAsynchProcessor
  5. Request: The IAsynchProcessor wrapper containing your response (object)
  6. Response: Contains custom objects or fields
share|improve this answer
Okay...so WHY was this voted down? These classes are indeed valid examples of long-polling. –  Prisoner ZERO Sep 28 '11 at 17:36
Real long-polling is not (simply) the practice of increasing the interval wherin you conduct a normal-poll (on a resource). It is part of a larger pattern...which is "somewhat" subject to interpretation...but only in certain areas of the overall implementation. That said...these classes follow said pattern! So if you have a reason for voting this down...I truly would be interested in the reason. –  Prisoner ZERO Jun 12 '12 at 19:05
Perhaps it was voted down as it does not directly address the question of a simple code example. Of course I did not vote it down so I can only guess. –  Andrew Jun 15 '12 at 15:22
add comment

Here is a simple long-polling example in PHP by Erik Dubbelboer using the Content-type: multipart/x-mixed-replace header:


header('Content-type: multipart/x-mixed-replace; boundary=endofsection');

// Keep in mind that the empty line is important to separate the headers
// from the content.
echo 'Content-type: text/plain

After 5 seconds this will go away and a cat will appear...
flush(); // Don't forget to flush the content to the browser.


echo 'Content-type: image/jpg


$stream = fopen('cat.jpg', 'rb');

echo '

And here is a demo:


share|improve this answer
@dbr - Thanks for adding the code! –  jasdeepkhalsa Dec 8 '12 at 12:34
add comment

I used this to get to grips with Comet, I have also set up Comet using the Java Glassfish server and found lots of other examples by subscribing to cometdaily.com

share|improve this answer
add comment

Take a look at this blog post which has code for a simple chat app in Python/Django/gevent.

share|improve this answer
add comment

Below is a long polling solution I have developed for Inform8 Web. Basically you override the class and implement the loadData method. When the loadData returns a value or the operation times out it will print the result and return.

If the processing of your script may take longer than 30 seconds you may need to alter the set_time_limit() call to something longer.

Apache 2.0 license. Latest version on github https://github.com/ryanhend/Inform8/blob/master/Inform8-web/src/config/lib/Inform8/longpoll/LongPoller.php


abstract class LongPoller {

  protected $sleepTime = 5;
  protected $timeoutTime = 30;

  function __construct() {

  function setTimeout($timeout) {
    $this->timeoutTime = $timeout;

  function setSleep($sleep) {
    $this->sleepTime = $sleepTime;

  public function run() {
    $data = NULL;
    $timeout = 0;

    set_time_limit($this->timeoutTime + $this->sleepTime + 15);

    //Query database for data
    while($data == NULL && $timeout < $this->timeoutTime) {
      $data = $this->loadData();
      if($data == NULL){

        //No new orders, flush to notify php still alive

        //Wait for new Messages
        $timeout += $this->sleepTime;
        echo $data;


  protected abstract function loadData();

share|improve this answer
add comment

Thanks for the code, dbr. Just a small typo in *long_poller.htm* around the line

1000 /* ..after 1 seconds */

I think it should be

"1000"); /* ..after 1 seconds */

for it to work.

For those interested, I tried a Django equivalent. Start a new Django project, say lp for long polling:

django-admin.py startproject lp

Call the app msgsrv for message server:

python manage.py startapp msgsrv

Add the following lines to settings.py to have a templates directory:

import os.path
PROJECT_DIR = os.path.dirname(__file__)
    os.path.join(PROJECT_DIR, 'templates'),

Define your URL patterns in urls.py as such:

from django.views.generic.simple import direct_to_template
from lp.msgsrv.views import retmsg

urlpatterns = patterns('',
    (r'^msgsrv\.php$', retmsg),
    (r'^long_poller\.htm$', direct_to_template, {'template': 'long_poller.htm'}),

And msgsrv/views.py should look like:

from random import randint
from time import sleep
from django.http import HttpResponse, HttpResponseNotFound

def retmsg(request):
    if randint(1,3) == 1:
        return HttpResponse('Hi! Have a random number: %s' % str(randint(1,10)))

Lastly, templates/*long_poller.htm* should be the same as above with typo corrected. Hope this helps.

share|improve this answer
Actually, "15000" is the syntax error. setTimeout takes an integer as its 2nd parameter. –  Andrew Hedges Jun 21 '10 at 22:48
This answer needs work. It is the culmination of one or more comments and a separate answer or answers. –  George W Bush Sep 20 '12 at 5:40
add comment

If you don't want to handle the long polling by yourself. You can consider to use cloud services such as EZComet (Which I founded), here is a chatroom example in PHP

chatroom demo

It's very easy to use, all you have to do is to register and get an API key, then use it to push message in your PHP code

$username = $_POST['username'];
$message = $_POST['message'];
$msg = array(
    'username' => $username,
    'message' => $message

$tick = push_msg('your api key', 'demo', 'chatroom', @json_encode($msg));
echo "tick: $tick";

Then subscribe in your page

    user_name: 'demo', 
    channel: 'chatroom', 
    callback: callback,
    auto_tick: false,
    msg_type: 'json'
share|improve this answer
add comment

The WS-I group published something called "Reliable Secure Profile" that has a Glass Fish and .NET implementation that apparently inter-operate well.

With any luck there is a Javascript implementation out there as well.

There is also a Silverlight implementation that uses HTTP Duplex. You can connect javascript to the Silverlight object to get callbacks when a push occurs.

There are also commercial paid versions as well.

share|improve this answer
add comment

Here is a node.js example that comes with a jquery client. There's also instructions on setting it up on heroku.

share|improve this answer
add comment

For a ASP.NET MVC implementation, look at SignalR which is available on NuGet.. note that the NuGet is often out of date from the Git source which gets very frequent commits.

Read more about SignalR on a blog on by Scott Hanselman

share|improve this answer
add comment

You can try icomet(https://github.com/ideawu/icomet), a C1000K C++ comet server built with libevent. icomet also provides a JavaScript library, it is easy to use as simple as

var comet = new iComet({
    sign_url: 'http://' + app_host + '/sign?obj=' + obj,
    sub_url: 'http://' + icomet_host + '/sub',
    callback: function(msg){
        // on server push

icomet supports a wide range of Browsers and OSes, including Safari(iOS, Mac), IEs(Windows), Firefox, Chrome, etc.

share|improve this answer
add comment

Why not consider the web sockets instead of long polling? They are much efficient and easy to setup. However they are supported only in modern browsers. Here is a quick reference.

share|improve this answer
add comment

protected by Bill the Lizard Oct 16 '11 at 22:36

