Long polling - Message system

前端 未结 4 862
夕颜
夕颜 2021-02-02 01:06

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 Sim

4条回答
  •  后悔当初
    2021-02-02 01:24

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

提交回复
热议问题