HTML5 Server-Sent Events
HTML5 server-sent events allow web pages to get updates from the server.
Server-Sent Events - One-Way Messaging
Server-Sent events refer to web pages automatically getting updates from the server.
This was possible before, provided that the web page had to ask whether updates were available. With server-sent events, updates arrive automatically.
Examples: Facebook/Twitter updates, stock price updates, new blog posts, game 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
"
"
;
}
;
Try it »
Example analysis:
- Create a new EventSource object, then specify the URL of the page that sends the updates (in this example, "demo_sse.php")
- Each time an update is received, the onmessage event occurs
- When the onmessage event occurs, push the received data into the element with id "result"
Detecting Server-Sent Event Support
In the following example, we have written some extra code to detect browser support for server-sent events:
if(typeof(EventSource)!=="undefined")
{
// Browser supports Server-Sent
// Some code.....
}
else
{
// Browser does not support Server-Sent..
}
Server-Side Code Example
For the example above to work, you also need a server that can send data updates (such as PHP or ASP).
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
ASP Code (VB) (demo_sse.asp):
<%
Response.ContentType="text/event-stream"
Response.Expires=-1
Response.Write("data: " & now())
Response.Flush()
%>
Code explanation:
- Set the "Content-Type" header to "text/event-stream"
- Specify that the page is not cached
- Output the sent date (always starting with "data: ")
- Refresh the output data to the web page
EventSource Object
In the example above, we used the onmessage event to get messages. However, other events can also be used:
| Events | Description |
|---|---|
| onopen | When the connection to the server is opened |
| onmessage | When a message is received |
| onerror | When an error occurs |