HTML and CSS Reference
This simple pseudo code shows you how the same techniques
we used in the Message API can help with getting around the
limitations of plain text. The WebSocket API really is as simple
as that. All the negotiation is done out of sight by the browser
for you; all the buffering is done for you (though you can check
the current bufferedAmount on the socket). In fact, the communi-
cation process is even easier than setting up an XHR object!
These are situations where you want to have simple push-based
messages that come from the server. Server-Sent Events are well
suited to applications like real-time price updates, or latest head-
lines, or some real-time, one-way information that needs to get to
the browser. If you instead need real-time, two-way communica-
tion, you want WebSockets as we saw earlier in this chapter.
Server-Sent Events come through the EventSource object.
They're quite similar to WebSockets in their use. You create a
new EventSource , passing it a URL to connect to. The browser
immediately begins to establish a connection.
The EventSource object has a few simple events:
• Open: when the connection has been established
• Message: when a new message comes in—the event's data
property contains the raw message
• Error: if something goes wrong
What makes EventSource unique is the way it handles dropped
connections and message tracking.
If the EventSource connection is dropped for any reason, the API
automatically tries to connect. If you use message IDs, when the
EventSource reestablishes its connection it will tell the server
which message ID it last saw. This allows the server (if your
application requires it) to easily send the client the backlog of
messages it missed.
Say for instance you had created a real-time charting application
that tracked every time Bruce mentions his favourite pink cud-
dly toy on Twitter. This charting app will plot Bruce's sentiment
against the current time—so you know if he's happy with the
colour, texture, and general feel of the thing or not.