doujia4619 2015-06-04 13:51 采纳率: 0%
浏览 61

如何停止服务器发送的事件

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)."

";
  ob_get_flush();
  flush();
  sleep(1);
}
  • 写回答

2条回答 默认 最新

  • dtyz76562 2017-06-16 15:18
    关注

    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)."
    
    ";
        ob_get_flush();
        flush();
        sleep( rand ( 1 , 3 ) );
    }
    echo "data: END-OF-STREAM
    
    "; // Give browser a signal to stop re-opening connection
    ob_get_flush();
    flush();
    sleep(1); // give browser enough time to close connection
    
    评论

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊