The Solution: WebSockets


No doubt you’ve heard people talking about HTML5 and all its neat new features. Two of these new features directly apply to realtime web technologies and client server communication—a fantastic result demonstrating that the web standards organizations and browser vendors really do listen to our feedback.
Server-Sent Events and the EventSource API13 are a formalization of the HTTP streaming solution but there is one more solution that’s even more exciting.
You may have heard the term WebSockets a time or two. If you’ve never really looked into realtime before, WebSockets may not have shown up on your radar except as a buzzword in articles talking about all the great new features of HTML5. The reason why WebSockets are so exciting is that they offer a standardized way of achieving what we’ve been trying to do through Comet hacks for years. It means we can now achieve client server bidirectional realtime communication over a single connection. It also comes with built-in support for communication to be made cross-domain.
9781430246206_Fig01-05.jpg
Figure 1-5.  Websockets open a full-duplex connection, allowing bidirectional client server communication
The WebSocket specification is part of HTML5, which means that web developers can use the WebSocket protocol in modern browsers.14
According to the WHATWG,15 the WebSocket protocol defines a standardized way to add realtime communication in web applications:
The WebSocket protocol enables two-way communication between a user agent running untrusted code running in a controlled environment to a remote host that has opted-in to communications from that code. The security model used for this is the Origin-based security model commonly used by Web browsers. The protocol consists of an initial handshake followed by basic message framing, layered over TCP. The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g. using XMLHttpRequest or