HTML5 SSE

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.

Browser support


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:

Demo_sse.php code

Run the program and try it out

Instance resolution:

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.

Example

ASP code (VB) (demo_sse.asp):


Code explanation:

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

EventSource object

In the above example, we use the onmessage event to get the message. However, other events are also available: 
 
    Event    Description
   OnopenWhen the connection to the server is opened
   OnmessageWhen receiving a message
   OnerrorWhen an error occurs


Last Updated: 2018-07-06 12:32:44 By akshay

SHARE THIS

share_facebook share_twitter share_google_plus

Please Comment Here :