PHP longpolling不断运行 [英] PHP longpolling running endlessly

查看:142
本文介绍了PHP longpolling不断运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个具有聊天功能的网站,我需要跟踪在线和离线用户.为了跟踪在线用户,我正在使用此表

Iam building a website with chat functionality and I need to keep track of online and offline users. For keeping track of online users I am using this table

user_id |时间戳

user_id | timestamp

我每20秒钟更新一次所有在线用户的时间戳.因此,只需将当前时间戳与表中的时间戳进行比较,就可以找出谁都处于离线状态.

I update the timestamp every 20 seconds for all online users.So I can find out who all are offline by just by comparing the current timestamp with the timestamp in the table.

现在的问题是:我使用长时间轮询来更新用户的在线状态.也就是,当用户登录时,我对这个脚本运行ajax调用.

Now the problem is this: I used long polling to update the online status of the users.That is when the user logs in I run an ajax call to a script that looks like this.

<?php
set_time_limit(0);

while(1){
  updateUserTimestamp();
  sleep(20);
}
?>

上面的代码运行良好,但是问题是,即使用户关闭浏览器后,它仍会像幽灵进程一样继续运行,并不断更新时间戳并占用资源.我希望它在客户端关闭浏览器时停止浏览器.

The above code is working perfectly.But the problem is that even after the user closes the browser it continues running like a ghost process and keeps on updating the timestamp and taking up resources.I want it to stop when the client closes the browser.

请帮助.

推荐答案

尝试以下解决方案(请参见 connection_aborted()函数的文档):

Try the following solution (see the documentation on connection_aborted() function):

<?php
set_time_limit(0);

while(!connection_aborted()){
    updateUserTimestamp();
    sleep(20);
}

或者,您可以将脚本设置为在客户端关闭连接时中止.请参阅 ignore_user_abort 上的文档详细信息.

Alternatively, you can set your script to abort when the client closes the connection. See the documentation on ignore_user_abort for details.

但是,如果您可能有许多并发请求,那么也许是一个好主意

But if you may have many concurrent requests, then maybe it is a good idea to either

  1. 放弃使用长轮询来支持频繁的AJAX请求,或者
  2. 采用类似Node.js的服务器端解决方案,该解决方案不会在其他请求上使用大量资源.

这篇关于PHP longpolling不断运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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