php – How to make a request on the server using the COMET method?

Question:

I have a system, in which it displays files from the database, in list form.

I poll the database every 5 seconds using the Polling method.

How do I use the Comet method? Since this method is not asking for information from the server all the time.

Answer:

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

Here is a very basic example, which sends a simple string after 2-10 seconds. 1 in 3 chances of returning a 404 error (to show handling in the example that comes Javascript error)

msgsrv.php

<?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));
?>

Note: With a real website, running this on a regular web server such as Apache will quickly tie up all the "working 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 [twisted] ( http://twistedmatrix.com/trac/ ), which doesn't depend on one thread per request. [cometd] ( http://cometdproject.dojotoolkit.org/ ) is a popular one (which is available in several languages), and [Tornado] ( http://www.tornadoweb.org/ ) is a new framework made specifically for such tasks (which was built into FriendFeed's long polling code) … but as a simple example, Apache is more than enough! This script can 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 on the data. So you request the file and wait again, act on the data (and repeat)

What follows is an example of a page.. When the page loads, it sends the initial request to the msgsrv.php file.. If successful, we add the message to the # messages div, after a second we call the waitForMsg function again, which triggers the wait.

The second setTimeout 1 () is a really basic rate limiter, it works fine without it, but if msgsrv.php *always* returns immediately (with a syntax error for example) – you flood your browser and it can quickly freeze . This would be best done by checking that the file contains a valid JSON response, and/or maintaining a total execution of requests per minute/second, and stopping accordingly.

If the page fails, it appends the error to the # messages div, waits 15 seconds and then tries again (same as how we'll wait a second after each message)

The nice thing about this approach is that it's very tough. If the clients internet connection dies it will time out then try to reconnect – this is inherent how long voting works, no complicated error handling is required

Anyway, long_poller.htm , using the jQuery framework:

<html>
<head>
    <title>BargePoller</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <style type="text/css" media="screen">
      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;}
    </style>

    <script type="text/javascript" charset="utf-8">
    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 */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            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)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };

    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            BargePoll message requester!
        </div>
    </div>
</body>
</html>

Source: https://stackoverflow.com/questions/333664/how-to-implement-basic-long-polling

Scroll to Top