简体   繁体   English

在PHP中实现longpolling的最佳方法是什么?

[英]What is the best way to implement longpolling in PHP?

I want to have the server know when a client disconnects. 我想让服务器知道客户端何时断开连接。 therefore, I want to implement longpolling. 因此,我想实现longpolling。 the problem is: the simple solution of looping would consume a lot of resources, but I dont know a better way. 问题是:循环的简单解决方案将消耗大量资源,但是我不知道更好的方法。

Here's a solution if you want to stay away from WebSockets: 如果您想远离WebSocket,这是一个解决方案:

Have the client ping example.php with a unique id every 2 seconds or so. 每2秒左右让客户端ping example.php具有唯一的ID。

example.php will do this: example.php将执行以下操作:

  1. Write the current time in seconds, with the filename as the unique id of the client 以秒为单位写当前时间,文件名作为客户端的唯一ID
  2. sleep(4) 睡眠(4)
  3. Read the last time written 阅读上次写的时间
  4. If the difference between the current time, and the last time written is greater than 3 seconds, the user is disconnected. 如果当前时间和上次写入时间之间的时差大于3秒,则表明用户已断开连接。 Else, the user is connected. 否则,用户已连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM