Feature #4974

Updated by Benjamin Baer almost 4 years ago 

 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) 


     <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 */ 
             "<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 */