解决方法
您不想创建无限循环,但可以设置超时.基本上循环为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);