HTML5 Server-Sent Events prototyping - ambiguous error and repeated polling?
Asked Answered
I

8

14

I'm trying to get to grips with Server-Side Events as they fit my requirements perfectly and seem like they should be simple to implement, however I can't get past a vague error and what looks like the connection repeatedly being closed and re-opened. Everything I have tried is based on this and other tutorials.

The PHP is a single script:

<?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();
}

$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
?>

and the JavaScript looks like this (run on body load):

function init() {

    var source;
    if (!!window.EventSource) {
        source = new EventSource('events.php');
        source.addEventListener('message', function(e) {
            document.getElementById('output').innerHTML += e.data + '<br />';
        }, false);
        source.addEventListener('open', function(e) {
            document.getElementById('output').innerHTML += 'connection opened<br />';
        }, false);
        source.addEventListener('error', function(e) {
            document.getElementById('output').innerHTML += 'error<br />';
        }, false);
    }
    else {
        alert("Browser doesn't support Server-Sent Events");
    }
}

I have searched around a bit but can't find information on

  1. If Apache needs any special configuration to support server-sent events, and
  2. How I can initiate a push from the server with this kind of setup (e.g. can I simply execute the PHP script from CLI to give a push to the already-connected-browser?)

If I run this JS in Chrome (16.0.912.77) it opens the connection, receives the time, then errors (with no useful information in the error object), then reconnects in 3 seconds and goes through the same process. In Firefox (10.0) I get the same behaviour.

EDIT 1: I thought the issue could be related to the server I was using, so I tested on a vanilla XAMPP install and the same error comes up. Should a basic server configuration be able to handle this without modification / extra configuration?

EDIT 2: The following is an example of output from the browser:

connection opened
server time: 01:47:20
error
connection opened
server time: 01:47:23
error
connection opened
server time: 01:47:26
error

Can anyone tell me where this is going wrong? The tutorials I have seen make it look like SSE is very straightforward. Also any answers to my two numbered questions above would be really helpful.

Thanks.

Imaginable answered 30/1, 2012 at 21:26 Comment(6)
can you post your timed loop, the code provided is error free. Do you drop the EventSource object at any time?Baldhead
@tnt I won't be able to post the code until Monday, but there is no timed loop - default EventSource behaviour is to reconnect 3 seconds after the connection is lost. A single function (init(), above) is called once on body load which creates the connection, then the browser enters its connect-error-reconnect cycle all by itself.Imaginable
From W3C : Legacy proxy servers are known to, in certain cases, drop HTTP connections after a short timeout. To protect against such proxy servers, authors can include a comment line (one starting with a ':' character) every 15 seconds or so.Baldhead
@tnt thanks for the input, but I'm not sure this applies - my browser is talking directly to Apache 2.2.14 on localhost with near-default configuration. I assume the comment / 15 seconds suggestion means that the server should send a comment event every 15 seconds, but in my case the connection errors immediately after a single event is sent, not after any noticeable delay during which the connection could timeout.Imaginable
Another lead: look at cometd. With web socket, long polling. See this post: https://mcmap.net/q/240646/-using-comet-with-phpGesticulation
@Gesticulation thanks but comet / long-polling is my fallback, I'd really like to get SSE working correctly instead. There are some interesting points in the question you linked-to but right now I'm not concerned by resource use (I'm on local development platform and prod won't use apache)Imaginable
F
22

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.
Frohne answered 20/2, 2012 at 12:22 Comment(2)
superb, that's exactly what I wanted. I set the sleep to 3 and the connection drops after 60 seconds (possibly related to connection timeout in httpd.conf, or PHP max execution time?). I set this as the answer, but if you can figure out that connection error I'll gladly put another bounty on the question and send if your way. I must admit my next question was going to be how to send new events to the client after the initial connection is made - now I see that the PHP just has to never stop executing.Imaginable
Thanks, tomfumb! That parenthetical possibility was exactly what I needed to figure it out. There was nothing in any of my Apache config files, but that max_execution_time was pretty easy to find. I edited my answer to include options to extend the life of every EventSource connection.Frohne
P
2

Server Sent Events are easy only when it comes to the Javascript part. First of all a lot of tutorials on SSE in the internet are closing their connections in the server part. Be it PHP or Java examples. This is really astonishing because what you get then is just a different way of implementing a "Ajax Polling" system with a strictly defined payload structure (and some minor features like client retry values set by server side). You can easily implement that with a few lines of jQuery. No need for SSE then.

According to the spec of SSE, i would say that the retry shouldnt be the normal way of implementing a client side loop. For me SSE is a one way streaming method which relies on a server backend which does not close the connection after pushing the first data to the client.

In Java its useful to use Servlet3 Async spec in order to free the request thread immediately and do the processing / streaming in a different thread. This works so far but still i dont like the 30 seconds connection lifetime for the EventSource request. Even i am pushing data every 5 seconds, the connection will be terminated after 30 seconds (chrome, firefox). Of course SSE will reconnect per default after 3 seconds but still i dont think this is the way it should be.

One problem is that some Java MVC frameworks dont have the ability to keep the connection open after data sending, so that you end up coding to the bare Servlet API. After on 24hours on coding prototypes in Java, i am more or less dissapointed because the gain over a traditional jQuery-Ajax-loop is not THAT much. And the problem with polyfilling the SSE feature is also existant.

Protohuman answered 17/9, 2014 at 15:15 Comment(1)
yes, rather frustratingly a lot of tutorial writers assume you're using Node in the back-end and there is little consideration of how to work with other frameworks. SSE seems like a fantastic idea but for some reason momentum behind it seems a little weak.Imaginable
N
1

The problem is not a server side issue, this all happens on the client and is part of the spec (I know it sounds weird).

http://dev.w3.org/html5/eventsource/

"When a user agent is to reestablish the connection, the user agent must run the following steps. These steps are run asynchronously, not as part of a task. (The tasks that it queues, of course, are run like normal tasks and not asynchronously.)"

  1. Queue a task to run the following steps:
    1. If the readyState attribute is set to CLOSED, abort the task.
    2. Set the readyState attribute to CONNECTING.
    3. Fire a simple event named error at the EventSource object.

I can't see any need to have an error here, so I have modified your Init function to filter out the error event fired whilst connecting.

function init() {
                var CONNECTING = 0;
                var source;
                if (!!window.EventSource) {
                    source = new EventSource('events.php');
                    source.addEventListener('message', function (e) {
                        document.getElementById('output').innerHTML += e.data + '
'; }, false); source.addEventListener('open', function (e) { document.getElementById('output').innerHTML += 'connection opened
'; }, false); source.addEventListener('error', function (e) { if (source.readyState != CONNECTING) { document.getElementById('output').innerHTML += 'error
'; } }, false); } else { alert("Browser doesn't support Server-Sent Events"); } }
Needle answered 9/2, 2012 at 21:20 Comment(5)
I'm confused - aren't you just hiding the problem? From what I understand the EventSource connection should stay open until I close it. The issue here is that the connection is being regularly closed and then reopened. You say the behaviour I see is correct for when the client reestablishes the connection, but why does it need reestablishing in the first place? If the client reconnects to the server every 3 seconds this is no different from polling, and totally negates the benefits of push. I have edited my question to include the browser's output.Imaginable
Ok from what i have read the server needs to keep the connection open and push the data to the client, in the case of PHP by flushing the buffer. If the server does not keep hold of the connection the event source will retry, submitting the last event id supplied by the server, this is what causes the polling that is observed. At present the spec is in draft and I don’t know why there isn’t another event to distinguish between an actual problem and reconnecting.Needle
Also based on the link provided by @Gesticulation PHP doesn’t sound like a good solution for the event source if you intend to keep the connection open as you will need to keep one PHP thread per request.Needle
it sounds like we're back to the original question - if Apache needs any special configuration to support server-sent events. As I said to unludo the PHP/thread issue doesn't bother me as this is only a development setup. The production environment will probably be java-based. Right now I just need to prove the approach in the context of an existing application, but so far all I've proven is that it's not as simple as it looksImaginable
Fundamentally the ‘error’ event you’re getting isn’t a ‘true’ error. Nothing is actually going wrong here that requires any change/input. In my opinion this ‘error’ is a stupid way to handle this expected behaviour. That’s a bit harsh, but it is certainly misleading. Perhaps a better event would have been ‘reconnecting’. This is a semantic issue, it says ‘error’ so it looks like an error, but it could have said anything. There is no actual error here.Needle
C
0

There is no actual issue with the code, that I can see. The answer selected as correct, is then, incorrect.

This sums up the behavior mentioned in the question (http://www.w3.org/TR/2009/WD-html5-20090212/comms.html):

"If such a resource (with the correct MIME type) completes loading (i.e. the entire HTTP response body is received or the connection itself closes), the user agent should request the event source resource again after a delay equal to the reconnection time of the event source. This doesn't apply for the error cases that are listed below."

The problem lies with the stream. I've successfully kept a single EventStream open before in perl; just send the appropriate HTTP headers, and start sending stream data; never shutdown the stream server side. The issue is that it seems most HTTP libraries attempt to close the stream after its been opened. This will cause the client to attempt to reconnect to the server, which is fully standard compliant.

This means that it will appear that the problem is solved by running a while loop, for a couple of reasons:

A) The code will continue to send data, as if it were pushing out a large file B) The code (php server) will never have the chance to attempt to close the connection

However, the problem here is obvious: to keep the stream alive, a constant stream of data must be sent. This results in wasteful utilization of resources, and negates any benefits the SSE stream is supposed to provide.

I'm not enough of a php guru to know, but I'd imagine that something in the php server/later in the code is prematurely closing the stream; I had to manipulate the stream at Socket level with Perl to keep it open, since HTTP::Response was closing the connection, and causing the client browser to attempt to re-open the connection. In Mojolicious (another Perl web framework), this can be done by opening a Stream object and setting the timeout to zero, so that the stream never times out.

So, the proper solution here is not to use a while loop; it is to call the appropriate php functions for opening, and keeping open, a php stream.

Chelate answered 8/6, 2012 at 14:10 Comment(0)
I
0

I was able to do it by implementing a custom event loop. It seems that this html5 feature is not ready at all and has compatibility issues even with the latest version of google chrome. Here it is, working on firefox (can't get the message sent correctly on chrome) :

var source;

function Body_Load(event) {
    loopEvent();
}

function loopEvent() {
    if (source == undefined) {
        source = new EventSource("event/message.php");
    }
    source.onmessage = function(event) {
        _e("out").value = event.data;
        loopEvent();
    }
}

P.S. : _e is a function that calls document.getElementById(id);

Ignace answered 21/6, 2012 at 21:59 Comment(0)
S
0

According to the Spec, the 3 second reconnection is by design when the connection is closed. PHP with a loop should theoretically stop this but the PHP script will be running indefinitely and wasting resources. You should try to avoid using apache and php for SSE because of this issue.

The standard http response should close a connection once the response is sent. You can change this with the header "connection: keep-alive" which should tell the browser that the connection is meant to stay open although this can cause problems if you're using proxies.

node.js or something similar is a better engine to use for SSE rather than apache/php and since it's basically JavaScript, its pretty easy to get to grips with.

Scaphoid answered 24/10, 2012 at 11:4 Comment(0)
E
0

Server Sent Event as name suggests the data should be traveling from server to client if it has to reconnect every three seconds to retrieve data from server then it is no different than other polling mechanisms.The purpose of SSE is to alert client as soon as there is new data which client is unaware of.Since server closes connection even if header is keep-alive there is no other way than to run php script in infinite loop but with considerable thread sleep to prevent burden on server.Till now i don't see any other way out and its better than spamming server every 3 seconds for new data.

Embrasure answered 20/4, 2014 at 16:17 Comment(0)
C
0

I'm trying the same thing. With varying degrees of success.

  1. Had the same problem with Firefox, running the same js code as mentioned. Using the Nginx server and some PHP that exited(ie no continual loop), I could get messages back to a "Request" from firefox only once the PHP exited. Run the PHP as a script in PHP.exe and all is good on the concole, stings are printed when flushed. However, Nginx doesn't send the data until the PHP has completed. Tried adding extra \r\n\r\n and flush() or ob_flush() did not help. There is no pushing of data, as shown in Wireshark logs, just a delayed response packet to the GET.

Read that I need a "push" module for Nginx that requires a re-build from source.

So this is definitely an Nginx problem.

  1. Using a socket in 'C' I was able to push data to Firefox as expected, and the socket was kept open, and no messages were missed. However this has the disadvantage that I need to server the page.html and the events/stream from the same socket or firefox will not connect due to Cross Site Url problems. There are some ways around this in certain situations, but not for a iframe in a menu system. This approach did prove the point that the SSE does work with firefox and there are pushed packets in the wireshark log. Where option 1 only had request/reply packets.

All this said, I still don't have a solution. I've tried to remove the buffering on the PHP and Nginx. But still nothing until PHP finishes. Tried different header options, eg chunks didn't help either. I don't feel like writing a full blown http server in 'C' but this seems to be the only option that is working for me at the moment. I'm about to try Apache, but most write ups suggest that this is worse than Nginx at this job.

Cardiograph answered 27/11, 2015 at 1:12 Comment(2)
Since the post I've found some links ./ write ups that helped alot.Cardiograph
Since the post I've found some links ./ write ups that helped alot. [html5doctor.com/server-sent-events/] Lots of example pages and useful information on this subject. pushmodule.slact.net the Push module for Nginx.Cardiograph

© 2022 - 2024 — McMap. All rights reserved.