用jQuery和PHP实现长轮询 [英] Implementing long-polling with jQuery and PHP
问题描述
我想基于JavaScript(jQuery将用于AJAX)和PHP建立聊天.
I want to build a chat, based on JavaScript (jQuery will be used for AJAX) and PHP.
我听说这样做的一个好方法是使用长轮询.
I've heard a good way of doing this is to use long-polling.
我确实知道这个主意,但是我不知道如何在服务器端实现它.
I do understand the idea, but I don't know how to implement it on the server side.
无限循环听起来是个坏主意.
An infinite loop sounds like a bad idea.
推荐答案
您不想创建无限循环,但是可以设置超时.基本上循环X秒等待某种数据,如果没有发生,则向客户端发送响应,告诉客户端它需要发起一个新请求,该请求具有相同的超时时间.
You don't want to create an infinite loop, but you can set a timeout. Basically loop for X second waiting for some sort of data, and if that doesn't happen send a response to the client telling it that it needs to initiate a new request, which will have the same timeout period.
$source; // some data source - db, etc
$data = null; // our return data
$timeout = 30; // timeout in seconds
$now = time(); // start time
// loop for $timeout seconds from $now until we get $data
while((time() - $now) < $timeout) {
// fetch $data
$data = $source->getData();
// if we got $data, break the loop
if (!empty($data)) break;
// wait 1 sec to check for new $data
usleep(10000);
}
// if there is no $data, tell the client to re-request (arbitrary status message)
if (empty($data)) $data = array('status'=>'no-data');
// send $data response to client
echo json_encode($data);
这篇关于用jQuery和PHP实现长轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!