php - JavaScript - Server Side Event only works once

one text

I am working with this example

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

My PHP code

<?php
date_default_timezone_set("America/New_York");
header("Cache-Control: no-store");
header("Content-Type: text/event-stream");

$counter = rand(1, 10);
while (true) {
// Every second, send a "ping" event.

echo "event: ping\n";
$curDate = date(DATE_ISO8601);
echo 'data: {"time": "' . $curDate . '"}';
echo "\n\n";

// Send a simple message at random intervals.

$counter--;

if (!$counter) {
echo 'data: This is a message at time ' . $curDate . "\n\n";
$counter = rand(1, 10);
}

ob_end_flush();
flush();

// Break the loop if the client aborted the connection (closed the page)

if (connection_aborted()) break;

sleep(1);
}

My JavaScript

const evtSource = new EventSource("//mySite.com/test.php", {
  withCredentials: true,
});

evtSource.onopen = function () {
  console.log("Connection to server opened.");
};

evtSource.addEventListener("ping", (event) => {
  console.log("EventSource ping data [" + event.data + "]");
});

evtSource.onmessage = (event) => {
  console.log("EventSource data [" + event.data + "]");
};

evtSource.onerror = (err) => {
  console.error("EventSource failed:", err);
};

When ran, onopen is fired, and one event is received, the ping data. After the first event, nothing is received. No error is thrown.

I added a logging feature to the PHP code and can see that the PHP is generating new output, but the client isn't receiving the events.

I used the inspector in both Chrome and Firefox to monitor the events and try to catch any errors, but I wasn't able to see anything of concern.

Thoughts?

Thank you.

Source