HTML5 Server-Sent Events

HTML5 Tutorial

HTML5 Server-Sent Events

Completed

Server-Sent Events allows a web page for getting updates from a server.

Server-Sent Events - One Way Messaging

Completed

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

Completed

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

Completed

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:

  • Creation of a new EventSource object, and mention the URL of the page sending the updates (in this example "demo_sse.php")
  • Eacn and every time an update is received, the onmessage event occurs
  • During the occurance of an onmessage event, the received data will be entered into the element with id="result"

Check Server-Sent Events Support

Completed

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

Completed

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:

  • Set the "Content-Type" header to "text/event-stream"
  • It is specified that the page should not cache
  • The output of the data should be send (Always start with "data: ")
  • Flushing the output data back to the web page

The EventSource Object

Completed

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