php - 如何增加服务器发送事件的重新打开时间?
问题描述
我正在努力显示来自服务器发送事件的通知。我检查了每次浏览器在每次连接关闭后大约 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();
}
解决方案
现在我有我的答案了。
控制重新连接超时:
在关闭每个服务器发送的事件连接后,浏览器会在大约 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();
推荐阅读
- odoo - 更改不起作用
- ionic3 - 离子服务错误:“响应”类型上不存在属性“用户”
- javascript - Javascript 追加数组以创建嵌套数组
- javascript - Ember 嵌套路由但非嵌套模板
- unity3d - Unity Script API中关于ISerializationCallbackReceiver的问题
- ruby - 如何处理 ruby 中的 sqlite 查询的结果?
- ios - 错误:执行被中断,原因:内部 ObjC 异常断点(-5)
- django - 在序列化程序中更改创建时的返回类型
- jquery - JQuery 中的动画问题
- android - 在 dao room 数据库中创建一个带有 body 的自定义函数