O'Reilly logo

Smashing Node.js: JavaScript Everywhere, 2nd Edition by Guillermo Rauch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.listen(app);

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) {

  console.log(obj.my);

});

Transports

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required