If the php runs in a loop with sleep(5) and sends messages to the client each 5 second iteration, the client receives the messages properly. However it presents an error when the loop ends and the connection is closed:
test.html:22 Error occurred: Event {isTrusted: true, type: 'error', target: EventSource, currentTarget: EventSource, eventPhase: 2, …}
I could ignore the error since at that point I am done with the server-sent events. However, when I have the server doing a long process and send messages to the client as certain chunks of processing are completed, it seems like the connection is dropped within 2 seconds and it attempts to reconnect. None of the messages are received at the client end. I see no errors anywhere. (server logs, xdebug step through, dev-tools step-through, console on client side)
What am I missing? Is there a server requirement that XAMPP default install does not include?
html/js
- Code: Select all
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script>
function initializeSSE()
{
var eventSource = new EventSource('test.php');
eventSource.onopen = function(event)
{
console.log('Connection opened:', event);
}
eventSource.onmessage = function(event)
{
console.log('Message received:', event.data);
}
eventSource.onerror = function(event)
{
console.error('Error occurred:', event);
eventSource.close();
};
eventSource.onclose = function(event)
{
console.log('Connection closed:', event);
// Attempt to reopen the connection after a short delay (e.g., 5 seconds)
setTimeout(initializeSSE, 5000);
};
}
initializeSSE();
</script>
</body>
</html>
PHP
- Code: Select all
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
function sendSSE($data) {
echo "data: $data\n\n";
ob_flush();
flush();
}
$interval = 5;
$i = 3;
while ($i > 0) {
sleep($interval);
sendSSE($i);
$i--;
}
echo "event: close\ndata:\n\n";
@ob_flush();
flush();
?>