I want to write a realtime server log viewer and just learned about SSE. I'm confused as to how to use it properly though. I'm running a Linux server with php 5.4. I have this code right now:
HTML + JS:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id='el'></ul>
<script type="text/javascript">
var eSource = new EventSource("ssedemo.php");
eSource.onmessage = function(event) {
var e = document.createElement("li");
e.innerHTML = event.data;
document.getElementById('el').appendChild(e);
};
</script>
</body>
</html>
PHP:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
ob_flush();
flush();
?>
This works, but it drops the connection after each update and the client re-establishes it every 3 seconds. I would like it to update faster. From the documentation and tutorials online, it seems that the proper way to use SSE is to wrap the server code in a loop to maintain the connection, and use sleep
to control the update time:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while(true) {
$time = date('r');
echo "data: The server time is: {$time}\n\n";
ob_flush();
flush();
sleep(1);
};
?>
The problem is that this doesn't work. Whenever I introduce a loop, onmessage
is never called on the client side. I have tried numerous examples without altering any code (https://github.com/html5rocks/www.html5rocks.com/tree/master/content/tutorials/eventsource/basics/static/demo), (https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events), etc, but none of them work unless I remove the loop from the php.
Why can't I maintain the connection? Did something change in php 5.4 that prevents this from working?