如何停止服务器发送的事件 [英] How to stop Server-Sent Events

查看:272
本文介绍了如何停止服务器发送的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有一个javascript代码,可以通过Server-Sent事件监听PHP代码,它工作正常,响应是通过循环从服务器发送的,当循环结束时,Server-Sent事件停止了,但是几秒钟脚本再次监听之后.当服务器端的循环也结束时,如何结束服务器发送的事件?谢谢.

Hello I have a javascript code that listens to a PHP code via Server-Sent Events, it is working well the response is sent from the server trough a loop and when the loop ends the Server-Sent Events stops however a few seconds after the script is again listening. how can I end the Server-Sent Events when the loop from the server side ends too? Thanks.

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);
}

推荐答案

我已经添加了其他内容(希望可以解决此问题) 您必须从服务器传递一条消息以关闭连接. 否则,当执行完成时,浏览器将以新的连接启动

Hi I've added extra to (hopefully fix this) You have to pass from the server a message to close the connection. Otherwise when the execution finishes the browser will start with a new connection

航空代码

air code

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

这篇关于如何停止服务器发送的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆