Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server sent events work, but with a massive time delay

Ill start off by saying this works perfectly on my local machine, the js example below connects to stream.php and receives a continuous update of the servers current time every second.

index.php

var source = new EventSource("stream.php");

source.addEventListener('message', function(e) {
    console.log(e);
}, false);

source.addEventListener('open', function(e) {
    console.log(e);
}, false);

source.addEventListener('error', function(e) {
    if (e.readyState == EventSource.CLOSED) {
        console.log('closed');
    }
}, false);

stream.php

while(true)
{
    // Headers must be processed line by line.
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    // Set data line
    print "data: " . date( 'G:H:s', time() ) . PHP_EOL . PHP_EOL;

    // Toilet
    flush();

    // Wait one second.
    sleep(1);
}

I did expect a bit of a delay after uploading to the live dev. server. But there is a time delay of about 15 to 20 min. before I even see the first entry.

The connection does not drop. (Prob. been going 40 min. + now.) Is this just an Apache looping problem (means it time to look at web sockets) or is there something I can do to fix this?

like image 347
CodeChap Avatar asked Sep 06 '12 10:09

CodeChap


1 Answers

Server.php needs to be as follows:

stream.php

while(true)
{
    // Headers must be processed line by line.
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    // Set data line
    print "Event: server-time" . PHP_EOL;
    print "data: " . date( 'G:H:s', time() ) . PHP_EOL;
    print PHP_EOL;

    ob_end_flush();     // Strange behaviour, will not work
    flush();            // Unless both are called !

    // Wait one second.
    sleep(1);
}
like image 101
CodeChap Avatar answered Sep 28 '22 06:09

CodeChap