Server-Sent Events allows a web page for getting updates from a server.
Server-Sent Events - One Way Messaging
A server-sent event is used when a web page is automatically getting updates from a server.
Eventhough it was also possible earlier, but the web page would have to verify if any updates were available. Using the server-sent events, the updates will be coming automatically.
Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.
Browser Support
The table numbers specify the first browser version which fully support server-sent events.
API | |||||
---|---|---|---|---|---|
SSE | 6.0 | Not supported | 6.0 | 5.0 | 11.5 |
Receive Server-Sent Event Notifications
The EventSource object is used for receiving server-sent event notifications:
Example
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
Try it Yourself
Example explained:
Check Server-Sent Events Support
In the tryit example given above there are some extra lines of code for checking browser support for server-sent events:
if(typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
// Some code.....
}
else {
// Sorry! No server-sent events support..
}
Server-Side Code Example
For the example given above to work properly, you will be needing a server which is capable of sending data updates (like PHP or ASP).
The server-side event stream syntax is very simple. Set the "Content-Type" header to "text/event-stream". Now you can send event streams.
Code given in PHP (demo_sse.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();
?>
Code in ASP (VB) (demo_sse.asp):
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
Code explained:
The EventSource Object
In the examples given above, the onmessage event is used to get messages. But, other events are also available:
Events | Description |
---|---|
onopen | while opening a connection to the server |
onmessage | While receiving a message |
onerror | while an error occurs |