HTML5 Server-Sent Events
HTML5 server-sent events allow web pages to obtain updates from a server.
Server-Sent Events - One-way Message Delivery
Server-Sent Events refer to web pages automatically obtaining updates from a server.
This was also possible before, provided that the web page had to ask whether there were available updates. With server-sent events, updates can arrive 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
Try it »
Example explanation:
- Create a new EventSource object, then specify the URL of the page sending 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 wrote additional code to detect browser support for server-sent events:
if(typeof(EventSource)!=="undefined")
{
// 浏览器支持 Server-Sent
// 一些代码.....
}
else
{
// 浏览器不支持 Server-Sent..
}
Server-side Code Example
For the above example to work, you also need a server capable of sending data updates (such as PHP and 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 event streams.
Example
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 not to cache the page
- Output the sent date (always starting with "data: ")
- Flush 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:
| Event | Description |
|---|---|
| onopen | When the connection to the server is opened |
| onmessage | When a message is received |
| onerror | When an error occurs |