Reputation: 21
I have built an application that, at some point, uses Server Sent Events, send from a long running php script, to update a progress bar on the frontend. After I have faced the typical problems with flushing the output of the php script and tried all the possible solutions I've read about at SO, I concluded that the only way to make it work was by forcing the output out by echoing a long string of spaces. The function that sends the messages to the browser is the following:
function sendMsg($id, $array) {
echo "id: $id" . PHP_EOL;
echo "data: ".json_encode($array).PHP_EOL;
echo PHP_EOL;
flush();
ob_flush();
echo str_repeat(' ', 4096);
}
The headers of the script are the following:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
Everything seemed to work great on the PCs I use, but when I tested the application on my sister's laptop I noticed this strange behavior with Firefox and Chrome. After having received the first 2 messages, they drop the connection. Firefox tries to reconnect and Chrome throws an error that says:
EventSource response has a MIME type ("text/html") that is not "text/event-stream"
The versions of the browsers are exactly the same (39.0 and 43.0.2357.134m respectively) in all PCs. My sister's laptop runs Windows 7 Home Premium SP1.
How can this different behavior be explained? Does it depend on the browsers' settings or could it be attributed to some system wide settings? IE 10 on my sister's laptop doesn't present the problem.
Upvotes: 2
Views: 4288
Reputation: 614
header('Cache-Control: no-cache');
header('Content-Type: text/event-stream; charset=utf-8');
$id=111;
$arr=[333,444,555];
echo "id: $id" . PHP_EOL;
echo "data: ".json_encode($arr).PHP_EOL;
echo 'retry: 2000', PHP_EOL, PHP_EOL; //2000 is miliseconds
Upvotes: 0