HTML5 Server-Sent Events
HTML5 Server-Sent Events allow a web page to get updates from the server.
Server-Sent Events - One-Way Messaging
Server-Sent Events refer to the web page automatically receiving updates from the server.
This was possible before, but the web page had to ask if updates were available. With Server-Sent Events, updates can reach the web page automatically.
Examples: Facebook/Twitter updates, stock price updates, new blog posts, sports results, etc.
Browser Support
All major browsers support Server-Sent Events, except Internet Explorer.
Receiving Server-Sent Event Notifications
The EventSource object is used to receive server-sent event notifications:
Example
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
Example explanation:
Create a new EventSource object, then specify the URL of the page sending the updates (in this case, "demo_sse.php")
Each time an update is received, the onmessage event occurs
When the onmessage event occurs, the received data is pushed into the element with the id "result"
Detecting Server-Sent Event Support
The following example shows how to detect browser support for Server-Sent Events:
if (typeof(EventSource) !== "undefined") {
// Browser supports Server-Sent Events
// Some code...
} else {
// Browser does not support Server-Sent Events
}
Server-Side Code Example
For the above example to work, you need a server capable of sending data updates (e.g., PHP and ASP).
The syntax for the server-side event stream is straightforward. Set the "Content-Type" header to "text/event-stream". Now, you can start sending the event stream.
Example
<?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();
?>
ASP Code (VB) (demo_sse.asp):
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: " & now())
Response.Flush()
%>
Code explanation:
Set the header "Content-Type" to "text/event-stream"
Specify that the page should not be cached
Output the date sent (always starts with "data: ")
Refresh the output data to the web page
EventSource Object
In the above example, we used the onmessage event to get messages. However, there are other events you can use:
Event | Description |
---|---|
onopen | When the connection to the server opens |
onmessage | When a message is received |
onerror | When an error occurs |