Search code examples
phplong-polling

Long polling - Message system


I'm looking into doing some long polling with jQuery and PHP for a message system. I'm curious to know the best/most efficient way to achieve this. I'm basing is off this Simple Long Polling Example.

If a user is sitting on the inbox page, I want to pull in any new messages. One idea that I've seen is adding a last_checked column to the message table. The PHP script would look something like this:

query to check for all null `last_checked` messages
if there are any...
while(...) {
    add data to array
    update `last_checked` column to current time
}
send data back

I like this idea but I'm wondering what others think of it. Is this an ideal way to approach this? Any information will be helpful!

To add, there are no set number of uses that could be on the site so I'm looking for an efficient way to do it.


Solution

  • Yes the way that you describe it is how the Long Polling Method is working generally. Your sample code is a little vague, so i would like to add that you should do a sleep() for a small amount of time inside the while loop and each time compare the last_checked time (which is stored on server side) and the current time (which is what is sent from the client's side).

    Something like this:

    $current = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
    $last_checked = getLastCheckedTime(); //returns the last time db accessed
    
    while( $last_checked <= $current) {
        usleep(100000);
        $last_checked = getLastCheckedTime();
    }
    
    $response = array();
    $response['latestData'] = getLatestData() //fetches all the data you want based on time
    $response['timestamp'] = $last_checked;
    echo json_encode($response);    
    

    And at your client's side JS you would have this:

    function longPolling(){
            $.ajax({
              type : 'Get',
              url  : 'data.php?timestamp=' + timestamp,
              async : true,
              cache : false,
    
              success : function(data) {
                    var jsonData = eval('(' + data + ')');
                    //do something with the data, eg display them
                    timestamp  = jsonData['timestamp'];
                    setTimeout('longPolling()', 1000);
              },
              error : function(XMLHttpRequest, textstatus, error) { 
                        alert(error);
                        setTimeout('longPolling()', 15000);
              }     
           });
    }