javascript 为什么我在php中使用js server sent events时会看到未指定的sse错误?

zbdgwd5y  于 2023-10-14  发布在  Java
关注(0)|答案(2)|浏览(185)

我正在设置一个系统,其中我使用JS Server-Sent_Events与PHP。而且效果很好。但是在每一次运行中,错误事件都会被触发一次,我不明白为什么。
我的JS:

  1. var source = new EventSource("serverSideEvents.php");
  2. source.onmessage = function(event) {
  3. var data = $.parseJSON(event.data);
  4. $(data).each(function(){
  5. doSomethingWith(this); //works as expected
  6. });
  7. };
  8. source.onerror = function(event) {
  9. console.log(event); //fires every few seconds don't know why
  10. };

我的php:

  1. <?php
  2. header('Content-Type: text/event-stream');
  3. header('Cache-Control: no-cache');
  4. sendUpdates( );
  5. function sendUpdates() {
  6. $controller = new someController();
  7. $out = $controller->Run();
  8. foreach($out as $msg)
  9. sendSSEMessage($msg['id'], 'data:'.json_encode($msg));
  10. }
  11. function sendSSEMessage( $id, $data ){
  12. echo "id: $id \n$data \n\n";
  13. ob_flush();
  14. flush();
  15. }

这工作正常,在PHP或浏览器上,PHP不会抛出错误,但每次运行PHP时都会触发js SSE的错误事件。这是控制台中的错误:

  1. Event {isTrusted: true, type: "error", target: EventSource, currentTarget: EventSource, eventPhase: 2, …}
  2. bubbles:false
  3. cancelBubble:false
  4. cancelable:false
  5. composed:false
  6. currentTarget:
  7. EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …}
  8. defaultPrevented:false
  9. eventPhase:0
  10. isTrusted:true
  11. path:[]
  12. returnValue:true
  13. srcElement:EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …}
  14. target:EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …}
  15. timeStamp:1129162.5250000001
  16. type:"error"
  17. __proto__:Event

要澄清的是:代码按预期工作。我得到了我需要的服务器消息。而且触发错误事件。

h7appiyu

h7appiyu1#

错误通常是由于服务器错误和关闭连接,或者当连接被服务器简单地关闭时(当服务器脚本完成时发生),
我认为正确的方法是在客户端也关闭连接,
所以在我的客户端,我正在做:

  1. <script>
  2. // Open a new EventSource connection to the SSE server
  3. const eventSource = new EventSource('/My_SSE_URL');
  4. // Event listener for messages received from the SSE server
  5. eventSource.onmessage = function (event) {
  6. // Handle received event message
  7. };
  8. eventSource.onerror = function(error) {
  9. // Close the connection in case of an error
  10. eventSource.close(); // <---- This is what you want to do
  11. console.error('Error occurred:', error);
  12. // Handle the SSE connection error as needed
  13. // For example, you can display an error message to the user
  14. };
  15. </script>
展开查看全部
mfpqipee

mfpqipee2#

好吧,多亏了sitePoint。每当服务器关闭连接时(脚本终止时),都会触发错误事件。然后浏览器再次启动。
所以为了防止这种情况,我们必须通过将其发送到一个循环中来保持我们的php活着,并最终根据php.ini中的max_run_time由服务器终止它,或者在定义的重新运行次数后自行终止它。这样做可能有助于减少浏览器重新连接时发生的开销。但要注意,运行脚本(睡眠或不睡眠)会给服务器负载带来负担。所以如果你有很多联系,这可能是不可取的。
当然,我们也可以忽略错误。

相关问题