HTML5 SSE
HTML5 Server-Sent Events
HTML5 server-sent event allows web pages to get updates from the server.
Server-Sent event-one-way messaging
The Server-Sent Event (SSE) 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.
Browser support
All major browsers support the server to send events, except Internet Explorer.
Receive Server-Sent event notification
The EventSource object is used to receive event notifications sent by the server:
Example
var source=new EventSource("demo_sse.php"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br>"; };
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.
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"
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 a message is received |
onerror | When an error occurs |