为什么我使用带有 php 的 js 服务器发送事件看到未指定的 sse 错误?

Why am I seeing unspecified sse errors using js server sent events with php?

我正在建立一个系统,我在其中使用 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();
}

这工作正常,在 cli 或浏览器上 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

明确一点:代码按预期工作。我得到了我需要的服务器消息。而且还会触发错误事件。

好的,明白了,感谢 sitePoint。 每次服务器关闭连接时都会触发错误事件,只要脚本终止就会发生这种情况。然后浏览器重试。

因此,为了防止这种情况发生,我们必须将 php 置于循环中,并最终根据 php.ini 中的 max_run_time 由服务器终止它,或者我们自己终止它在定义的重新运行次数之后。 这样做可能有助于减少浏览器重新连接时发生的开销。但请注意 运行 脚本(休眠与否)会给您的服务器负载带来负担。所以如果你有很多连接,这可能是不可取的。

当然我们也可以直接忽略这个错误