Reputation: 1099
I am trying to understand how does HTML5 server side event works ? In the below code why would it not print Hello ? But if i remove the comments on the server side time line in php it would work and keep displaying the server side time?
HTML5
<div id="result"></div>
<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("php/demo_sse.php");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br>";
};
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
PHP
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "Hello";
//echo "data: The server time is: {$time}\n\n";
flush();
?>
Upvotes: 2
Views: 2169
Reputation: 31919
There is one detail, which you must be aware, this is the
Event Stream Format
Sending an event stream from the source is a matter of constructing a plain text response, served with a text/event-stream
Content-Type, that follows the SSE
(Server-Sent Events) format. In its basic form, the response should contain a "data:" line, followed by your message, followed by two \n
characters to end the stream:
data: My message\n\n
Multiline Data
If your message is longer, you can break it up by using multiple "data:" lines. Two or more consecutive lines beginning with "data:" will be treated as a single piece of data, meaning only one message event will be fired.
Each line should end in a single \n
(except for the last, which should end with two). The result passed to your message handler is a single string concatenated by newline characters. For example:
data: first line\n
data: second line\n\n
will produce first line\nsecond line
in e.data
.
One could then use e.data.split('\n').join('')
to reconstruct the message sans \n
characters.
So much of the theory, back to your problem, just write:
echo "Hello"."\n\n";
EDIT:
Controlling the Reconnection-timeout
The browser attempts to reconnect to the source roughly 3 seconds after each connection is closed. You can change that timeout by including a line beginning with retry:
, followed by the number of milliseconds to wait before trying to reconnect.
The following example attempts a reconnect after 10 seconds:
retry: 10000\n
data: hello world\n\n
Cancel an Event Stream
Normally, the browser auto-reconnects to the event source when the connection is closed, but that behavior can be canceled from either the client or server.
To cancel a stream from the client, simply call:
source.close();
To cancel a stream from the server, respond with a non text/event-stream
Content-Type or return an HTTP status other than 200 OK
(e.g. 404 Not Found
).
Both methods will prevent the browser from re-establishing the connection.
Official documentation is here and a word of security is here.
Upvotes: 4