javascript - How to stop Server-Sent Events -
hello have javascript code listens php code via server-sent events, working response sent server trough loop , when loop ends server-sent events stops few seconds after script again listening. how can end server-sent events when loop 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 server 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 $c){ echo "data: ".json_encode($c)."\n\n"; ob_get_flush(); flush(); sleep(1); }
hi i've added (hopefully fix this) have pass server message close connection. otherwise when execution finishes browser start 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 server 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 $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 signal stop re-opening connection ob_get_flush(); flush(); sleep(1); // give browser enough time close connection
Comments
Post a Comment