HTML5 server send event (Server-Sent Events)
The 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 a web page that automatically gets updates from the server.
This may have been done before, provided that the web page had to ask if there were any updates available. Updates can be reached automatically by sending events through the server.
Examples: Facebook/Twitter updates, valuation updates, new blog posts, event results, and more.
All major browsers support server sending events, except Internet Explorer.
Receive Server-Sent event notifications
The EventSource object is used to receive notifications sent by the server:
Run the program and try it out
Create a new EventSource object and then specify the URL of the page that sent the update (in this case, "demo_sse.php")
The onmessage event occurs every time an update is received
When the onmessage event occurs, push the received data into the element with the id "result"
Detect Server-Sent event support
In the following example, we wrote an extra piece of code to detect the browser support for the server to send events:
Server-side code instance
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 event streams.
ASP code (VB) (demo_sse.asp):
Set the header "Content-Type" to "text/event-stream"
Specifies not to cache the page
Output send date (always starting with "data: ")
Refresh output data to web page
In the above example, we use the onmessage event to get the message. However, other events are also available:
|Onopen||When the connection to the server is opened|
|Onmessage||When receiving a message|
|Onerror||When an error occurs|