Implementing long-polling with jQuery and PHP

只谈情不闲聊 提交于 2019-12-03 20:27:17

问题


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.


回答1:


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



回答2:


implementing such kind of chat is not good idea in php, you can use CometChat, Nodjs and if you can not install scripts on your server than you can use Available APIs for Realtime Sending Data,

such as Pubnub, Pushemr, Beaconpush.



来源:https://stackoverflow.com/questions/12918925/implementing-long-polling-with-jquery-and-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!