我正在努力显示来自服务器发送事件的通知。我检查了浏览器每次在关闭每个连接大约3秒后尝试重新与源连接。该事件的通话速度太快,因此我的服务器也被加载。
因此,如何更改重新开放时间以增加?我必须至少执行60秒,所以告诉我该怎么做?
我正在尝试以下代码。
<table class="table" id="notification"></table>
<script type="text/javascript">
var ssevent = null;
if (!!window.EventSource) {
ssevent = new EventSource('ssevent.php');
ssevent.addEventListener('message', function(e){
if(e.data){
json = JSON.parse(e.data);
if(json){
json.forEach(function(v,i){
html = "<tr><td>"+ v.text +"</td><td>"+ v.date +"</td></tr>";
});
$('#notification').append(html);
}
}
}, false);
ssevent.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED){
console.log("Connection was closed.");
}
}, false);
} else {
console.log('Server-Sent Events not support in your browser');
}
</script>
事件流的文件如下。
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include_once "config.php";
$time = isset($_SESSION['last_event_time']) ? $_SESSION['last_event_time'] : time();
$result = $db->quesry("SELECT * FROM event_noti WHERE event_time < {$time} ")->rows;
$_SESSION['last_event_time'] = time();
if($result){
$json = array();
foreach ($result as $row){
$json[] = array(
'text' => $row['event_text'],
'date' => date("Y-m-d H:i", $row['event_time']),
);
}
echo "data: ". json_encode($json) . "\n\n";
flush();
}
根本上,您无法控制此设置:这是特定于浏览器的设置。
如果您的浏览器是Firefox,则似乎受以下设置控制:dom.server-events.default-reconnection-time
,默认值为5000ms。
后退一步:仅当服务器关闭连接时才发生重新连接。为什么要关闭连接? (*)为什么3秒的重新连接速度太快?
SSE的目的是使延迟最小化;折衷方案是更多地使用资源,特别是必须为每个客户端保持专用的套接字打开。
所以听起来您不想使用SSE,而是想在60秒的setInterval()
通话中使用简单的AJAX轮询?
*:如果确实打算保持打开状态,则需要包装查询并在while(true){...}
循环中处理结果代码。放例如在while循环结束时睡眠一秒钟,以阻止DB服务器超载。
现在我有我的答案。
关闭每个服务器发送的事件连接后,浏览器会在大约3秒钟内尝试将连接重新连接到源。在尝试重新连接之前,可以通过以retry:
开始行,然后添加要等待的毫秒数来更改该超时。
我更改了下面的代码,并根据需要开始工作。
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include_once "config.php";
$time = isset($_SESSION['last_event_time']) ? $_SESSION['last_event_time'] : time();
$result = $db->quesry("SELECT * FROM event_noti WHERE event_time < {$time} ")->rows;
$_SESSION['last_event_time'] = time();
echo "retry: 60000\n"; // 60 seconds, to wait for next connection.
$json = array();
if($result){
foreach ($result as $row){
$json[] = array(
'text' => $row['event_text'],
'date' => date("Y-m-d H:i", $row['event_time']),
);
}
}
echo "data: ". json_encode($json) . "\n\n";
flush();