Chapter 5. WebSockets

Every HTTP request sent from the browser includes headers, whether you want them or not. Nor are they small headers. Uncompressed request and response headers can vary in size from 200 bytes to over 2K. Although, typical size is somewhere between 700 and 900 bytes, those numbers will grow as userAgents expand features.

WebSockets give you minimal overhead and a much more efficient way of delivering data to the client and server with full duplex communication through a single socket. The WebSocket connection is made after a small HTTP handshake occurs between the client and the server, over the same underlying TCP/IP connection. This gives you an open connection between the client and the server, and both parties can start sending data at any time.

A few of WebSockets’ many advantages are:

  • No HTTP headers

  • No lag due to keep-alive issues

  • Low latency, better throughput and responsiveness

  • Easier on mobile device batteries

Building the Stack

To effectively develop any application with WebSockets, you must accept the idea of the “real-time Web” in which the client-side code of your web application communicates continuously with a corresponding real-time server during every user connection. To accomplish this, you can use a capable protocol such as WebSockets or SPDY to build the stack yourself. Or you can choose a service or project to manage the connections and graceful degradation for you. In this chapter, you’ll learn how to implement a raw WebSocket server and the ...

Get HTML5 and JavaScript Web Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.