Chapter 11: Socket.IO

As mentioned previously, getting WebSocket ready for your applications takes more than a simple implementation.

Socket.IO is a project I created that aims to solve the most common deficiencies of the simple implementation. It provides a great deal of flexibility while retaining a simple API:

Server API


io.sockets.on(‘connection’, function (socket) {

  socket.emit(‘my event’, { my: ‘object’ });


Browser/Client API

var socket = io.connect();

socket.on(‘my event’, function (obj) {




One of the most appealing features about Socket.IO is that communication is based on transports, not all of which are WebSocket, which means Socket.IO works on a large variety of browsers and devices, all the way from IE6 to iOS.

For example, you can utilize AJAX as a method for real-time communication when using a technique called long polling. Basically, this technique consists of making serial AJAX calls, but if the server doesn’t have any data to send you, the connection stays open for 20–50 seconds so that no extra data transfer due to HTTP request/response headers occurs.

Socket.IO automatically leverages complex and convoluted techniques such as long polling for you, without making the API any more complicated than WebSocket.

In addition, even if WebSocket is supported by the browser but blocked by proxies or firewalls, Socket.IO can still handle that situation gracefully.

Disconnected versus closed

Another fundamental ...

Get Smashing Node.js: JavaScript Everywhere, 2nd Edition 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.