【发布时间】:2015-06-16 17:10:46
【问题描述】:
我有一个连接器,它将使用 cURL 和 PHP 调用 RESP API。
我需要每秒调用一个方法来检查新消息然后处理它们。我使用以下两种方法来处理消息
- 使用
SetInterval()进行AJAX 轮询:每秒调用一次php 脚本。这非常有效,除非我无法阻止多个SetInterval()从浏览器的不同选项卡同时运行。 (我不想让用户打开 10 个浏览器选项卡,这会导致一个用户同时运行 10 个SetInterval()。 - 服务器使用
EventSource发送事件:一旦队列中有新数据,服务器将发送更新浏览器。这会减慢响应时间。我对脚本的每次调用都需要大约 20 多秒才能完成,这是一个问题。我不确定为什么会这样。
这是我的SetInterval() 实现
function startCalls(){
//update the screen using Intervals
refreshIntervalId = setInterval(function() {
$.getJSON("index.php", {'method': 'getMessages', 'jSON': true} , function(data){
processServerData(data);
});
}, 1000);
}
一旦用户登录,我就会调用这个函数startCalls()
在 index.php 文件中我有这个代码被调用
if($method == 'getMessages'){
$messaging = new ICWS\Messaging($icws);
$messaging->processMessages();
$myQueue = $messaging->getCallsQueue();
echo json_encode($myQueue );
}
这是我的第二个实现“服务器发送事件”
//Server Side Message Polling
function startPolling(evtSource){
evtSource.addEventListener("getMessagingQueue", function(e) {
var data = JSON.parse(e.data);
processServerData(data)
}, false);
}
一旦用户登录,我就会调用这个函数startPolling( new EventSource("poll.php") );
为简单起见,假设我的processServerData 方法如下所示
function processServerData(data){
console.log('process the data received from the server');
}
这是我的 php 代码
<?php
require 'autoloader.php';
//Make sure cURL is enabled on the server
if(!is_callable('curl_init')){
exit('cURL is disabled on this server. Before making API calls cURL extension must be enabled.');
}
if( isset($_COOKIE['icws_username']) ){
$user = trim($_COOKIE['icws_username']);
}
if( isset($_COOKIE['icws_password']) ){
$pass = trim($_COOKIE['icws_password']);
}
if( isset($_COOKIE['icws_station']) ){
$stationName = trim($_COOKIE['icws_station']);
}
if( !isset($user, $pass, $stationName) ){
echo json_encode(array('status' => 'The IC credentials you entered are invalid'));
exit;
}
$scheme = 'http';
$host = 'host';
$port = '8018';
$sleepTime = 1;
$url = sprintf('%s://%s:%s@%s:%s', $scheme, $user, $pass, $host, $port);
try {
header("Content-Type: text/event-stream\n\n");
session_start();
//configure the connection
$conf = new ICWS\Config\Config($url, $stationName);
//create a new instance of icws
$attrebutes = array();
$icws = new ICWS\Connection($conf, $attrebutes, true);
$messaging = new ICWS\Messaging($icws);
ob_end_clean();
while(true){
header("Content-Type: text/event-stream" . PHP_EOL);
header("Cache-Control: no-cache" . PHP_EOL);
$messaging->processMessages();
$result = $messaging->getCallsQueue();
//$current = $icws->getCurrentUserStatusQueue();
echo 'event: getMessagingQueue' . PHP_EOL;
echo 'data: ' . json_encode( $result) . PHP_EOL;
echo PHP_EOL; //required
ob_end_flush();
flush();
sleep(1);
}
} catch(Exception $e){
echo $e->getMessage();
}
?>
服务器似乎锁定了所有命中服务器的请求,直到我刷新页面后,“页面刷新”停止无限循环,其他请求立即处理
为什么 Server-Sent Event 会导致这样的问题?
不同类型的投票的绝佳资源can be found in this Question
【问题讨论】:
标签: javascript php jquery server-sent-events icws