Project

General

Profile

Feature #4974

Updated by Benjamin Baer almost 4 years ago

https://stackoverflow.com/questions/333664/how-do-i-implement-basic-long-polling 

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

 <pre> 
 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) 

 Javascript: 

 <pre> 
     <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> 
 </pre> 

Back