长轮询 - 消息系统

Sea*_*nWM 12 php long-polling

我正在考虑使用jQuery和PHP对消息系统进行一些长时间的轮询.我很想知道实现这一目标的最佳/最有效的方法.我基于这个简单的长轮询示例.

如果用户正坐在收件箱页面上,我想要提取任何新邮件.我见过的一个想法是last_checked在消息表中添加一列.PHP脚本看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

我喜欢这个想法,但我想知道别人怎么想.这是解决这个问题的理想方式吗?任何信息都会有所帮助!

要添加,网站上没有可用的设置数量,因此我正在寻找一种有效的方法.

Vas*_*kas 8

是的,您描述它的方式是长轮询方法通常如何工作.你的示例代码有点模糊,所以我想补充一点,你应该sleep()while循环内做一小段时间,每次比较last_checked时间(存储在服务器端)和current时间(这是什么从客户端发送).

像这样的东西:

$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);    
Run Code Online (Sandbox Code Playgroud)

在你的客户端JS你会有这样的:

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);
          }     
       });
}
Run Code Online (Sandbox Code Playgroud)