我正在设置一个系统,其中我使用JS Server-Sent_Events与PHP。而且效果很好。但是在每一次运行中,错误事件都会被触发一次,我不明白为什么。
我的JS:
var source = new EventSource("serverSideEvents.php");
source.onmessage = function(event) {
var data = $.parseJSON(event.data);
$(data).each(function(){
doSomethingWith(this); //works as expected
});
};
source.onerror = function(event) {
console.log(event); //fires every few seconds don't know why
};
我的php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
sendUpdates( );
function sendUpdates() {
$controller = new someController();
$out = $controller->Run();
foreach($out as $msg)
sendSSEMessage($msg['id'], 'data:'.json_encode($msg));
}
function sendSSEMessage( $id, $data ){
echo "id: $id \n$data \n\n";
ob_flush();
flush();
}
这工作正常,在PHP或浏览器上,PHP不会抛出错误,但每次运行PHP时都会触发js SSE的错误事件。这是控制台中的错误:
Event {isTrusted: true, type: "error", target: EventSource, currentTarget: EventSource, eventPhase: 2, …}
bubbles:false
cancelBubble:false
cancelable:false
composed:false
currentTarget:
EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …}
defaultPrevented:false
eventPhase:0
isTrusted:true
path:[]
returnValue:true
srcElement:EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …}
target:EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …}
timeStamp:1129162.5250000001
type:"error"
__proto__:Event
要澄清的是:代码按预期工作。我得到了我需要的服务器消息。而且触发错误事件。
2条答案
按热度按时间h7appiyu1#
错误通常是由于服务器错误和关闭连接,或者当连接被服务器简单地关闭时(当服务器脚本完成时发生),
我认为正确的方法是在客户端也关闭连接,
所以在我的客户端,我正在做:
mfpqipee2#
好吧,多亏了sitePoint。每当服务器关闭连接时(脚本终止时),都会触发错误事件。然后浏览器再次启动。
所以为了防止这种情况,我们必须通过将其发送到一个循环中来保持我们的php活着,并最终根据php.ini中的max_run_time由服务器终止它,或者在定义的重新运行次数后自行终止它。这样做可能有助于减少浏览器重新连接时发生的开销。但要注意,运行脚本(睡眠或不睡眠)会给服务器负载带来负担。所以如果你有很多联系,这可能是不可取的。
当然,我们也可以忽略错误。