HTML 5 SSE [Server Send Event]

HTML5 server-sent event allows web pages to get updates from the server.

Server-Sent event-one-way messaging

The Server-Sent event refers to the web page automatically getting updates from the server.

It was possible to do this in the past, provided that the web page had to ask if an update was available. By sending events through the server, updates can arrive automatically.

Examples: Facebook/Twitter updates, stock price updates, new blog posts, event results, etc.

Receive Server-Sent event notification

The EventSource object is used to receive event notifications sent by the server:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Novice Tutorial</title>
</head>
<body>
<h1>Obtain server-side update data</h1>
<div id="result"></div>

<script>
if(typeof(EventSource)!=="undefined")
{
	var source=new EventSource("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>

</body>
</html>

Example analysis:

  • Create a new EventSource object, and then specify the URL of the page where the update will be sent (“demo_sse.php” in this example)
  • Every time an update is received, an onmessage event occurs
  • When the onmessage event occurs, push the received data into the element with id “result”

Detect Server-Sent event support

In the following example, we have written an additional piece of code to detect the browser support of the server sending events:

if(typeof(EventSource)!=="undefined")
{
    // Browser supports Server-Sent
    // Some code.....
}
else
{
    // The browser does not support Server-Sent...
}

Server-side code example

In order for the above example to work, you also need a server (such as PHP and ASP) that can send data updates.

The syntax of the server-side event stream is very simple. Set the “Content-Type” header to “text/event-stream”. Now you can start sending the event stream.

<?php
header ( 'Content-Type: text/event-stream' );
header ( 'Cache-Control: no-cache' );

$time  =  date ( 'r' );
echo  "data: The server time is:  { $time } nn" ;
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”
  • Specifies not to cache the page
  • Output sending date (always start with “data: “)
  • Refresh the output data to the web page

EventSource object

In the above example, we use the onmessage event to get the message. However, other events can also be used:

Event
Description
onopen

When the connection to the server is opened

onmessage

When the message is received

onerror

When an error occurs