Elmer
Elmer

Reputation: 85

simple server sent-event: clock stop after 30 minutes

I would make a simple clock with sent-event my code is: The client and server is on LAN, and the browser is iceweasel v.38.7.1.

php:

<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");
function sendMsg($msg) {
  echo "retry: 1000\n";
  echo "data: $msg" .PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}
sendMsg(date("H:i", time()));

js

(function get_time()
{var source = new EventSource('/config/rtc/get_time.php');

source.addEventListener('message',function (event)
  {document.getElementById("orologio").innerHTML=event.data;},false);

source.addEventListener('error', function(event) { 
if (event.readyState === EventSource.CLOSED)
{get_time();}},false);
})();

The clock work for 30-45 minutes, after it stop,
Where I did go wrong?
thanks.

Upvotes: 3

Views: 383

Answers (1)

Darren Cook
Darren Cook

Reputation: 28928

Your PHP script should look like:

<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");
function sendMsg($msg) {
  echo "retry: 1000\n";
  echo "data: $msg" .PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}
while(true){
   sendMsg(date("H:i", time()));
   sleep(1);
   }

Otherwise your PHP script is constantly closing (which totally does away with the point of using SSE), the SSE socket closes, and the browser then auto-reconnects. Theoretically ad infinitum, but possibly something gets fed up after 30 minutes :-)

What I thought the problem was going to be was script time-out. So at the top of your PHP script you should add:

set_time_limit(0);

Again, this is saying you want the PHP script to run forever, that the infinite loop is by design, and not a mistake.

Upvotes: 1

Related Questions