Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. It consists of:
- a Node.js server: Source | API
There are also several client implementation in other languages, which are maintained by the community:
- Java: https://github.com/socketio/socket.io-client-java
- C++: https://github.com/socketio/socket.io-client-cpp
- Swift: https://github.com/socketio/socket.io-client-swift
- Dart: https://github.com/rikulo/socket.io-client-dart
- Python: https://github.com/miguelgrinberg/python-socketio
- .Net: https://github.com/Quobject/SocketIoClientDotNet
The client will try to establish a WebSocket connection if possible, and will fall back on HTTP long polling if not.
WebSocket is a communication protocol which provides a full-duplex and low-latency channel between the server and the browser. More information can be found here.
So, in the best-case scenario, provided that:
- the browser supports WebSocket (97% of all browsers in 2020)
- there is no element (proxy, firewall, …) preventing WebSocket connections between the client and the server
you can consider the Socket.IO client as a “slight” wrapper around the WebSocket API. Instead of writing:
const socket = new WebSocket("ws://localhost:3000");
You will have, on the client-side:
const socket = io("ws://localhost:3000");
The API on the server-side is similar, you also get a
socket object which extends the Node.js EventEmitter class:
const io = require("socket.io")(3000);
Socket.IO provides additional features over a plain WebSocket object, which are listed below.
But first, let’s detail what the Socket.IO library is not.
Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.
// WARNING: the client will NOT be able to connect!
There are also talks to include a WebSocket server in the Node.js core.
On the client-side, you might be interested by the robust-websocket package.
Here are the features provided by Socket.IO over plain WebSockets:
- reliability (fallback to HTTP long-polling in case the WebSocket connection cannot be established)
- automatic reconnection
- packet buffering
- broadcasting to all clients or to a subset of clients (what we call “Room”)
- multiplexing (what we call “Namespace”)
Please find more details about how it works here.