How to stop server-sent events

Hello, I have javascript code that listens for PHP code through Server-Sent Events, it works well, the response is sent from the server through the loop, and when the loop completes the Server-Sent events, it stops, however, for a few seconds after listening to the script again . how can I end Server-Sent Events when the server side loop 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); } 
+1
source share
1 answer

Hi, I added extra (I hope to fix this) You must send a message from the server to close the connection. Otherwise, when execution ends, 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 
0
source

Source: https://habr.com/ru/post/921060/


All Articles