HTML5 Server-Sent Events prototyping – ambiguous error and repeated polling?

The problem is your php.

With the way your php script is written, only one message is sent per execution. That’s how it works if you access the php file directly, and that’s how it works if you access the file with an EventSource. So in order to make your php script send multiple messages, you need a loop.

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function sendMsg($id, $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: $msg" . PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}
while(true) {
  $serverTime = time();
  sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
  sleep(1);
}
?>

I have altered your code to include an infinite loop that waits 1 second after every message sent (following an example found here: Using server-sent events).

This type of loop is what I’m currently using and it eliminated the constant connection drop and reconnect every 3 seconds. However (and I’ve only tested this in chrome), the connections are now only kept alive for 30 seconds. I will be continuing to figure out why this is the case and I’ll post a solution when I find one, but until then this should at least get you closer to your goal.

Hope that helps,

Edit:

In order to keep the connection open for ridiculously long times with php, you need to set the max_execution_time (Thanks to tomfumb for this). This can be accomplished in at least three ways:

  1. If you can alter your php.ini, change the value for “max_execution_time.” This will allow all of your scripts to run for the time you specify though.
  2. In the script you wish to run for a long time, use the function ini_set(key, value), where key is ‘max_execution_time’ and value is the time in seconds you wish your script to run for.
  3. In the script you wish to run for a long time, use the function set_time_limit(n) where n is the number of seconds that you wish your script to run.

Leave a Comment