 |
HTML 5 Server-sent Events
Server-sent events standardizes and formalizes how a continuous stream of data can be sent from a server to a browser. Server-sent events is designed to enhance native, cross-browser streaming. Server-sent events introduces eventsource, a new HTML DOM element that connects to a server URL to receive an event stream as shown in the following example:
<eventsource src="http: onmessage="alert(event.data)" >
A connection to the server stocks.kaazing.com is established and when this server sends an event stream, a message event is dispatched on the eventsource element. For example, if the server sends the following event (where \n represents a newline character):
event: message\n
data: {'KZNG': 1.01}\n
\n
Then the eventsource element in the browser dispatches a message event with a data attribute that contains the string:
In this case, the stock price for KZNG is received by the client and displayed on the page.
Additionally, if the server includes the id header for an event, then the client adds a Last-Event-ID header when it reconnects, so that the event stream can resume without repeating or missing any events when the HTTP response completes, thus guaranteeing message delivery. The HTTP response can complete normally or else abruptly, if the underlying TCP connection is broken due to some network error. Furthermore, the server can control how long the client must wait before reconnecting by specifying an optional retry header as part of an event in the event stream.
Learn more about HTML 5 and Server-sent Events.
|
|
|
|