I'm creating an infopage for work that updates "live".
Now I came across Server Sent Events.
I managed to put data on the screen but the update was every 3 seconds (after looking online it appears I created a disconnect and the default retry time was 3 seconds).
I found a solution that in theory should work but when putting it live, it creates an overload on the server side.
<?php
// make session read-only
session_start();
session_write_close();
// disable default disconnect checks
ignore_user_abort(true);
// set headers for stream
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Access-Control-Allow-Origin: *");
// Is this a new stream or an existing one?
$lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
if ($lastEventId == 0) {
$lastEventId = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : 0);
}
echo ":" . str_repeat(" ", 2048) . "\n"; // 2 kB padding for IE
echo "retry: 1000\n";
// start stream
while(true){
if(connection_aborted()){
exit();
} else{
// here you will want to get the latest event id you have created on the server, but for now we will increment and force an update
$latestEventId = $lastEventId+1;
if($lastEventId < $latestEventId){
echo "id: " . $latestEventId . "\n";
echo "data: Howdy (".$latestEventId.") \n\n";
$lastEventId = $latestEventId;
ob_flush();
flush();
} else{
// no new data to send
echo ": heartbeat\n\n";
ob_flush();
flush();
}
}
// 2 second sleep then carry on
sleep(1);
}
?>
It appears that the while(true) loop is the problem ...
Unfortunately, I couldn't find the correct way to use Server Side events with a connection that stays open.
Is there someone that knows a solution for this?
I tried using this script without while loop (which works) BUT that's because the client side keeps reconnecting after every 3 seconds, so basically the connection opens, closes, opens, closes