Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Server-Sent Events

Tags:

javascript

php

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);
}
like image 273
oussama kamal Avatar asked Jun 04 '15 13:06

oussama kamal


People also ask

How do you stop responding to events in a stream?

Cancel an event stream # close(); To cancel a stream from the server, respond with a non text/event-stream Content-Type or return an HTTP status other than 200 OK (e.g. 404 Not Found ). Both methods will prevent the browser from re-establishing the connection.

How do I stop EventSource?

The close() method of the EventSource interface closes the connection, if one is made, and sets the EventSource. readyState attribute to 2 (closed). Note: If the connection is already closed, the method does nothing.

How do server-sent events work?

So what are Server-Sent Events? A client subscribes to a “stream” from a server and the server will send messages (“event-stream”) to the client until the server or the client closes the stream. It is up to the server to decide when and what to send the client, for instance, as soon as data changes.


1 Answers

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;
 }
}
like image 79
Vijesh Avatar answered Oct 13 '22 13:10

Vijesh