HTML5 Server Sent Events - HTML 5

What is the use of server sent events in HTML5?

Conservative web applications generate events which can be dispatched to the web server. For example for clicking on a link requests a new page from the server.

Type of events which are flowing between different web browsers can be called as client-sent events.

Along with HTML5, WHATWG Web Applications 1.0 introduced events which flow between different web servers and are called Server-Sent Events (SSE). Using SSE user can push DOM events continuously from the web server to the visitor's browser.

Event streaming approach opens a determined connection to the server by sending data to the client whenever a new information is available and thus eliminates the need for constant polling.

Server-sent events can standardize the way of data streaming from server to client.

Web Application for SSE

To use Server-Sent Events in a web application user should add an <eventsource> element to the document.

The src attribute of <eventsource> element should point to an URL which provides a persistent HTTP connection to send data stream containing the events.

URL points to a PHP, PERL or any Python script which takes care of sending event data persistently. Below is a simple example of web application which expects server time.

Server Side Script for SSE

A server side script should send Content-type header specifying the type text/event-stream as shown below.

print "Content-Type: text/event-stream\n\n";

After setting Content-Type, server side script sends an Event: tag followed by event name. Below example sends Server-Time as event name ended with a new line character.

print "Event: server-time\n";

Last step is to send event data using Data: tag which is followed by an integer of string value ending with a new line character as shown below

Handle Server-Sent Events

Below is an example for modifying the web application to handle server-sent events

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

HTML 5 Topics