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 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测