Search code examples
phpserver-sent-events

Server-Sent Evenets: Change time interval


I was looking at Server-Sent Events, since the client is on shared hosting and I can't use websockets.

I have tested an W3School's example and it is working beautifuly.My code looks like this:

Index.php (relevant section):

<script>
    var source=new EventSource("data.php");
    source.onmessage=function(event)
    {
        document.getElementById("result").innerHTML+=event.data + "<br>";
    };
</script>

Data.php:

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

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Now, the output i get looks like this:

The server time is: Wed, 24 Apr 2013 13:31:25 +0200
The server time is: Wed, 24 Apr 2013 13:31:28 +0200
The server time is: Wed, 24 Apr 2013 13:31:31 +0200
The server time is: Wed, 24 Apr 2013 13:31:34 +0200
The server time is: Wed, 24 Apr 2013 13:31:37 +0200
The server time is: Wed, 24 Apr 2013 13:31:40 +0200
The server time is: Wed, 24 Apr 2013 13:31:43 +0200
The server time is: Wed, 24 Apr 2013 13:31:46 +0200
The server time is: Wed, 24 Apr 2013 13:31:49 +0200

I have noticed, that time-interval here is 3 seconds.
My question is: How can I change this time interval?
In the data.php I intend to have a code that sends a request and gets back a response, but the number of requests is limited, so I need to make that interval bigger.

Is this even a good way of solving a problem, or should I use polling?

Sorry if I wasn't clear enough, I'm really not sure how to describe the problem.
Thank you!


Solution

  • You may not like this, but the fact is - you are not using it correctly.

    The PHP script shouldn't terminate - you should use a loop. With this loop, you can also control the interval (the easiest way would be to sleep($seconds)).

    while(true) {
       $time = date('r');
       echo "data: The server time is: {$time}\n\n";
       flush();
       sleep(3);   // interval: 3 seconds
    }
    

    The reason your script seems to work is that the browser always tries to reestablish a connection, because the event-stream terminated (considered an error by the browser). However, this isn't different than just polling the server every X seconds, eliminating the advantage of event streams.

    Also, Apache and PHP are not recommended to use for event-streams - Apache isn't designed for connections that remain open indefinitely (This may no longer be true - haven't kept up to date), and many hosters restrict the execution time for PHP scripts. Either use a different web server, or use polling, to avoid potential problems.