最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop Server-Sent Events - Stack Overflow

programmeradmin6浏览0评论

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

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);
}
Share Improve this question asked Jun 4, 2015 at 13:51 oussama kamaloussama kamal 1,0373 gold badges23 silver badges46 bronze badges 6
  • See this: stackoverflow./questions/7636165/… – Qantas 94 Heavy Commented Jun 4, 2015 at 13:58
  • 1 There is nothing about the solution I'm looking for in the link ! – oussama kamal Commented Jun 4, 2015 at 14:06
  • Key line: "Should it want to, it may terminate the connection and respond with a 204 No Content next time the client tries to connect. This will cause the client to stop trying to reconnect." Please try and read it next time. – Qantas 94 Heavy Commented Jun 4, 2015 at 14:10
  • I tried to add Connection: keep-alive but same issue still reconnection after the loop ends, also the link points to a node JS code not PHP – oussama kamal Commented Jun 4, 2015 at 14:12
  • Keep-Alive has nothing to do with HTTP status codes, what do you mean? – Qantas 94 Heavy Commented Jun 4, 2015 at 14:12
 |  Show 1 more ment

3 Answers 3

Reset to default 6

You could use a boolean variable isOpenOnce = false in your javascript and then in your sse.onopen set isOpen to true the first time. In the beginning check the flag and close connection if true. This way no need of server side changes.

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

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

the simple and easy way to stop a sse=new EventSource() from running or even stop it from loading multiple times is just to check the window variable and if it exists, close it.

if (typeof window.sse !== 'undefined') sse.close();

done!

发布评论

评论列表(0)

  1. 暂无评论