Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Server-Sent Events onerror showing up every 3 seconds

I'm new on SSE and I'm following the w3schools tutorial. I added some code to their example so I can see when the connection is opened and when some error occours. Here is my code:

<script>
var source = new EventSource("sse.php");                        
source.addEventListener('message', function(e) {
    console.log("onmessage");           
    document.getElementById("result").innerHTML += event.data + "<br>";     
}, false);

source.addEventListener('open', function(e) {
    console.log("onopen");
}, false);

source.addEventListener('error', function(e) {
    console.log('error '+e.readyState);
}, false);

</script>

And my server-side code:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

The documentation says that

A server-sent event is when a web page automatically gets updates from a server. This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.

But the console shows us the opposite:

enter image description here

The client-side is requesting a new connection, getting the message, an error is occurring and the connection is closed. This is repeated every 3 seconds. Why is this happening?

like image 757
aseolin Avatar asked Aug 25 '15 11:08

aseolin


1 Answers

I suspect that your server side implementation is not holding the HTTP connection open. So it is reconnecting over and over again.

I don't write PHP but every example I've found uses ob_flush() in addition to flush().

ob_flush();
flush();

Have you tried that?

like image 116
baynezy Avatar answered Sep 24 '22 01:09

baynezy