php - 长轮询 - 消息系统

标签 php long-polling

我正在考虑使用 jQuery 和 PHP 为消息系统进行一些长轮询。我很想知道实现这一目标的最佳/最有效的方法。我的基地是这个Simple Long Polling Example .

如果用户位于收件箱页面,我想提取任何新消息。我看到的一个想法是向消息表添加一个 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

我喜欢这个想法,但我想知道其他人对此有何看法。这是解决这个问题的理想方法吗?任何信息都会有帮助!

补充一点,网站上的使用次数没有设定,因此我正在寻找一种有效的方法来做到这一点。

最佳答案

是的,您描述的方式就是长轮询方法的一般工作方式。 您的示例代码有点模糊,所以我想补充一点,您应该在 while 循环内执行少量的 sleep() 时间,并每次进行比较last_checked 时间(存储在服务器端)和当前 时间(从客户端发送的时间)。

类似这样的事情:

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

在你的客户端 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);
          }     
       });
}

关于php - 长轮询 - 消息系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15743388/

相关文章:

php - 仅在前端排队和本地化

php - 字符串日期当前日期/时间?

php - Apache 不会在轮询时提供服务

c# - 寻找 cometd 式服务器或客户端

jquery - 这是长轮询的当前实现吗?

php - Laravel Join 返回奇数值

php - ReflectionException Laravel 控制台命令

javascript - 如何在 jquery post 中返回数据?

node.js - 如何处理来自SQS的多条消息?

node.js - Apache 代理后面的 Sockjs/socketio 断开连接延迟