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:
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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With