使用jQuery和PHP实现长轮询

时间:2012-10-16 16:07:53

标签: php jquery chat comet long-polling

我想基于JavaScript(jQuery将用于AJAX)和PHP构建聊天。

我听说这样做的好方法是使用长轮询。

我理解这个想法,但我不知道如何在服务器端实现它。

无限循环听起来像个坏主意。

2 个答案:

答案 0 :(得分:7)

您不想创建无限循环,但可以设置超时。基本上循环为X秒等待某种数据,如果没有发生,则向客户端发送响应,告知它需要发起一个新的请求,这将具有相同的超时时间。

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

答案 1 :(得分:0)

在PHP中实现这种聊天并不是一个好主意,您可以使用CometChatNodjs,如果您无法在服务器上安装脚本,那么您可以使用可用API实时发送数据,

,例如PubnubPushemrBeaconpush