【问题标题】:How to stop Server-Sent Events如何停止服务器发送的事件
【发布时间】:2015-06-04 13:51:55
【问题描述】:

您好,我有一个通过服务器发送事件监听 PHP 代码的 javascript 代码,它运行良好,响应是通过循环从服务器发送的,当循环结束时,服务器发送事件会停止几秒钟脚本再次收听后。当服务器端的循环也结束时,如何结束服务器发送的事件?谢谢。

JS:

var sse=new EventSource("data.php");
            sse.onmessage=function(event){
                document.getElementById("map").innerHTML+=event.data;              
            };

PHP:

<?php
header('Content-Type: text/event-stream'); //indicates that server is aware of server sent events
header('Cache-Control: no-cache');//disable caching of response

$coordinates = [  
   [  
      "20:11",
      33.5731235,
      -7.6433045
   ],
   [  
      "20:11",
      33.5731054,
      -7.6432876
   ],
   [  
      "20:11",
      33.5731644,
      -7.6433304
   ]
];

foreach($coordinates as $c){  
  echo "data: ".json_encode($c)."\n\n";
  ob_get_flush();
  flush();
  sleep(1);
}

【问题讨论】:

  • 链接中没有我正在寻找的解决方案!
  • 关键行:"如果它愿意,它可能会在客户端尝试连接时终止连接并以204 No Content 响应。这将导致客户端停止尝试重新连接。”请下次尝试阅读。
  • 我尝试添加 Connection: keep-alive 但同样的问题在循环结束后仍然重新连接,并且链接指向节点 JS 代码而不是 PHP
  • Keep-Alive与HTTP状态码无关,什么意思?

标签: javascript php


【解决方案1】:

您可以在您的 javascript 中使用布尔变量 isOpenOnce = false,然后在您的 sse.onopen 中首次将 isOpen 设置为 true。一开始检查标志并关闭连接,如果为真。这种方式不需要服务器端更改。

var isOpenOnce = false;
sse.onopen = function() {
 if(isOpenOnce) {
  sse.close();
 }else {
  console.log("Connection to server opened.");
  isOpenOnce = true;
 }
}

【讨论】:

    【解决方案2】:

    您好,我已经添加了额外内容(希望能解决这个问题) 您必须从服务器传递一条消息才能关闭连接。 否则,当执行完成时,浏览器将开始一个新的连接

    航空代码

    JS:

    var sse=new EventSource("data.php");
    sse.onmessage=function(event){
        if ('END-OF-STREAM' == event.data) {
            sse.close(); // stop retry
        }
        document.getElementById("map").innerHTML+=event.data;
    };
    

    PHP:

    <?php
    header('Content-Type: text/event-stream'); //indicates that server is aware of server sent events
    header('Cache-Control: no-cache');//disable caching of response
    
    $coordinates = [
       [
          "20:11",
          33.5731235,
          -7.6433045
       ],
       [
          "20:11",
          33.5731054,
          -7.6432876
       ],
       [
          "20:11",
          33.5731644,
          -7.6433304
       ]
    ];
    
    foreach($coordinates as $c){
        echo "data: ".json_encode($c)."\n\n";
        ob_get_flush();
        flush();
        sleep( rand ( 1 , 3 ) );
    }
    echo "data: END-OF-STREAM\n\n"; // Give browser a signal to stop re-opening connection
    ob_get_flush();
    flush();
    sleep(1); // give browser enough time to close connection
    

    【讨论】:

    • 无需发送“数据:END-IF-STREAM”。只需发送一个事件,例如“事件:关闭”,然后使用 sse.addEventListener('close', fucntion(){ sse.close(); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2018-09-24
    • 2020-06-20
    • 1970-01-01
    • 2015-09-24
    • 2015-06-16
    相关资源
    最近更新 更多