i tried to create my own SSE using php and js, but don’t receive data each second instead,
get all data after 1min , OR my browser create each 5 second new request :
PHP : (https://github.com/mdn/dom-examples/blob/main/server-sent-events/index.html)
header("X-Accel-Buffering: no");
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$counter = rand(1, 10); // a random counter
while (1) {
// 1 is always true, so repeat the while loop forever (aka event-loop)
$curDate = date(DATE_ISO8601);
echo "event: pingn",
'data: {"time": "' . $curDate . '"}', "nn";
// Send a simple message at random intervals.
$counter--;
if (!$counter) {
echo 'data: This is a message at time ' . $curDate, "nn";
$counter = rand(1, 10); // reset random counter
}
// flush the output buffer and send echoed messages to the browser
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
// break the loop if the client aborted the connection (closed the page)
if (connection_aborted()) break;
// sleep for 1 second before running the loop again
sleep(1);
}
JS :
var source = new EventSource("sse2");
source.onmessage = function (event) {
console.log(event.data);
};
any advise to fix that.