Server Sent Events - Quick JavaScript Interview Questions (2015)

Quick JavaScript Interview Questions (2015)

Chapter 16. Server Sent Events

Q. What is Server Side Events (SSE)?
ANSWER
HTML5 provides server side events feature by which a web page gets the update from the server automatically. A great example of this feature is Facebook notification or Google + updates.

Q. What is the content type of the server sent response? ANSWER
The content type of the server response is “text/event-stream” for the “Content-Type” header.

Q. How to create an event source for listening to server updates? ANSWER
An event source can be created by instantiating the object of EventSource class with a server path. The syntax for creating an event source is listed below.

var source = new EventSource(“<URL to Server>”);

Q. What are the event types is fired by an EventSource? ANSWER
An EventSource fires 3 different events. Callback methods can be attached to the source for listening to these events. These event types are listed below.

onopen : This event is fired when the server open the connection to the browser.
onmessage: This event is fired when server produces the new output to the stream.
onerror: This event is fired when an error occurs by some means.

Q. How to close an event stream?
ANSWER
The event stream can be closed using close() method.

Q. What is the format of event stream?
ANSWER
The event stream is a simple stream of text data, which must be encoded using UTF-8. Each message is separated by a pair of newline characters. A colon as the first character of a line is, in essence, a comment, and is ignored.