I implement some code to query the database for any changes and to send an event. Here's the code of my PHP script
header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');
//****Some code here to query the database
echo "event: message\n";
echo "data: change_from_database \n";
echo "\n\n";
ob_flush();
flush();
I'm relying on the browser to automatically reconnect each time the connection closes, so I don't implement any loop on my server code. In addition, I learned from this thread that implementing an infinite loop has many disadvantages.
So everything works fine client-side: the browser reconnects each time the connection closes and an event is fired each time the server sends one; well except for Firefox (40.0.2) which doesn't reconnect. I know it doesn't because I wrote some JavaScript error checking code to test this:
var evtSource = new EventSource("../sse.php");
evtSource.onerror = function(event){
var txt;
switch( event.target.readyState ){
case EventSource.CONNECTING:
txt = 'Reconnecting...';
break;
}
console.log(txt);
}
So after like each second, the console on chrome for example logs "Reconnecting"
. Firefox on the other hand reconnects once and never does so again.
How do I write code to make this work on Firefox, and perhaps other browsers which support server-sent events but don't reconnect automatically?