Understanding Socket.IO

It's important to provide timely feedback to users in your web application. It all started with the introduction of XMLHttpRequest by Microsoft which became what we now know as AJAX. AJAX long-polling used to be the standard way to fetch server-sent data for an application, though it wasn't the most ideal solution. Long-polling involves sending periodic HTTP requests for data, introducing latency and increasing server load.

The IETF standardised WebSockets in 2011, providing a way for developers to send and receive data through a TCP socket. All major browsers began to roll out support for the standard, and developers started to use it in their projects.

Socket.IO is an event-based bi-directional communication layer for realtime web applications, built atop Engine.IO. It abstracts many transports, including AJAX long-polling and WebSockets, into a single API. It allows developers to send and receive data without worrying about cross-browser compatibility.

First Major Release

Socket.IO finally reached version 1.0 on the 28th of May, 2014. The Socket.IO project contained two parts before 1.0: a transport handling implementation, and a high-level API. Transport handling has been moved out into a separate, framework-agnostic project: Engine.IO. This allows other developers to build new APIs and projects for the realtime web without reinventing the wheel.

The global socket variable is an EventEmitter-like object. We can attach a listener to fire when we've connected to the server like so:

socket.on("connect", function () {
console.log("Connected!");
});

Sending and Receiving Objects

Since both the server and client's Socket object act as EventEmitters, you can emit and listen for events in a bi-directional manner. For example, we can emit a "tweet" event on the server and listen for it on the client side.

Further Reading

Socket.IO has played an important role in the popular adoption of Node.js by making WebSockets both accessible and reliable. Version 1.0 represents a major step in its evolution and the extraction of Engine.IO has opened up some interesting possibilities for the Node.js ecosystem.

We've only covered some of the features in Socket.IO in this article, you can read about the rest at the Socket.IO website: http://socket.io/docs/.