长轮询-邮件系统 [英] Long polling - Message system

查看:74
本文介绍了长轮询-邮件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

如果用户坐在收件箱页面上,我想提取任何新消息.我见过的一个想法是在消息表中添加last_checked列. PHP脚本如下所示:

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.

推荐答案

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

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

类似这样的东西:

$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端,您会得到以下信息:

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

这篇关于长轮询-邮件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆