socket.io, uws, websocket, and ws are all npm packages that enable real-time, bidirectional communication between clients and servers using the WebSocket protocol or compatible fallbacks. socket.io provides a high-level, feature-rich abstraction with automatic reconnection, rooms, and fallback to HTTP long-polling. ws is a lightweight, standards-compliant WebSocket implementation focused on performance and simplicity. The websocket package offers a lower-level, spec-aligned API with support for both client and server roles in Node.js. uws was an ultra-fast WebSocket implementation but has been officially deprecated and should not be used in new projects.
When building real-time web applications — like live chat, collaborative editors, or financial tickers — choosing the right WebSocket library is critical. The four packages under review (socket.io, uws, websocket, and ws) each take a different approach to enabling bidirectional communication. Let’s break down their technical trade-offs with real code examples.
uws Is No Longer ViableBefore diving into comparisons, note that uws is officially deprecated. According to its npm page and GitHub repository, the project has been archived, and the author states: “This project is no longer maintained. Please use the official uWebSockets.js bindings or switch to ws.” Despite past claims of extreme speed, uws should not be used in any new project due to lack of security updates, Node.js version compatibility, and active maintenance.
// ❌ Do NOT use uws in new code
// const uWS = require('uws'); // Deprecated — avoid
With that out of the way, let’s compare the three viable options.
socket.io: Adds a Layer on Top of WebSocketssocket.io doesn’t just use WebSockets — it wraps them in its own protocol that includes acknowledgments, namespaces, and event names. It also falls back to HTTP long-polling if WebSockets aren’t available.
// socket.io server
const io = require('socket.io')(3000);
io.on('connection', (socket) => {
socket.join('room1');
socket.emit('welcome', { msg: 'Hello!' });
socket.on('chat', (data) => {
io.to('room1').emit('message', data);
});
});
// socket.io client (browser)
const socket = io('http://localhost:3000');
socket.on('welcome', (data) => console.log(data.msg));
socket.emit('chat', { text: 'Hi everyone!' });
This abstraction simplifies common patterns but adds overhead: every message includes metadata like event names and packet IDs, increasing bandwidth usage.
ws: Pure WebSocket, Minimal Overheadws implements the WebSocket standard directly with no extra framing. It’s ideal when you control both client and server and want maximum efficiency.
// ws server
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
ws.send(JSON.stringify({ type: 'welcome' }));
ws.on('message', (data) => {
const msg = JSON.parse(data);
// Broadcast to all clients
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
});
// ws client (Node.js or browser with wrapper)
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => ws.send(JSON.stringify({ text: 'Hello' }));
ws.onmessage = (event) => console.log(JSON.parse(event.data));
Note: In browsers, you’d use the native WebSocket object; ws is primarily a server-side library (though it can be used in Node.js clients).
websocket: Low-Level Control with Full Spec ComplianceThe websocket package gives you fine-grained access to the WebSocket handshake and frame parsing. It’s more verbose but useful when you need to inspect or modify protocol details.
// websocket server
const WebSocketServer = require('websocket').server;
const http = require('http');
const server = http.createServer();
server.listen(8081);
const wsServer = new WebSocketServer({ httpServer: server });
wsServer.on('request', (request) => {
const connection = request.accept(null, request.origin);
connection.sendUTF(JSON.stringify({ type: 'welcome' }));
connection.on('message', (message) => {
if (message.type === 'utf8') {
const data = JSON.parse(message.utf8Data);
// Echo to sender
connection.sendUTF(message.utf8Data);
}
});
});
// websocket client (Node.js)
const WebSocketClient = require('websocket').client;
const client = new WebSocketClient();
client.on('connect', (connection) => {
connection.sendUTF(JSON.stringify({ text: 'Hi' }));
connection.on('message', (msg) => {
if (msg.type === 'utf8') console.log(JSON.parse(msg.utf8Data));
});
});
client.connect('ws://localhost:8081/');
This level of control is rarely needed in typical apps but can be essential for protocol testing or integration with non-standard clients.
socket.io automatically handles reconnection, heartbeat (ping/pong), and disconnection detection. You get this out of the box.// socket.io auto-reconnect is default behavior
const socket = io({
reconnection: true,
reconnectionAttempts: Infinity
});
ws requires manual ping/pong handling if you want to detect dead connections:// ws: manual heartbeat
wss.on('connection', (ws) => {
const interval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping();
}
}, 30000);
ws.on('close', () => clearInterval(interval));
});
websocket also leaves heartbeat logic to you, though it exposes raw ping/pong events.| Feature | socket.io | ws | websocket |
|---|---|---|---|
| Automatic reconnection | ✅ | ❌ | ❌ |
| Rooms/broadcasting | ✅ | ❌* | ❌ |
| Fallback to HTTP | ✅ | ❌ | ❌ |
| Native browser support | ✅ (via client lib) | ✅ (native WebSocket) | ❌ (Node-only client) |
| Message acknowledgment | ✅ | ❌ | ❌ |
| Compression (permessage-deflate) | ✅ | ✅ | ✅ |
* Broadcasting in ws requires manual iteration over wss.clients.
socket.io if you must support very old browsers (e.g., IE9) that lack WebSocket support — it gracefully degrades to long-polling.ws or websocket only if you can assume modern browser support (WebSocket has been widely supported since ~2012).socket.io emits clear events like 'connect_error', 'disconnect', and 'reconnect_failed'.ws uses standard 'error' and 'close' events but gives less context by default.websocket provides detailed error codes per RFC 6455 (e.g., 1002 for protocol error).socket.io when:ws when:websocket when:uws — it’s deprecated.For most real-world applications, ws is the sweet spot: fast, well-maintained, and close to the metal without unnecessary complexity. Reach for socket.io only when you truly need its higher-level features and are willing to accept the protocol overhead. Avoid uws entirely, and reserve websocket for niche, low-level use cases.
Remember: real-time doesn’t have to mean complicated. Sometimes, the simplest WebSocket implementation is the most powerful.
Choose socket.io if you need built-in features like automatic reconnection, room management, broadcasting, and fallback to HTTP long-polling for older browsers. It’s ideal for applications requiring rapid development of real-time features (e.g., chat apps, live dashboards) where developer productivity outweighs the need for minimal overhead. However, be aware that its custom protocol adds latency and bandwidth compared to raw WebSockets.
Do not choose uws for new projects — it is officially deprecated and unmaintained. The author archived the repository and recommends using ws instead. While it once offered extreme performance, lack of updates, security patches, and compatibility with modern Node.js versions makes it unsuitable for production use today.
Choose the websocket package if you need strict adherence to the WebSocket RFC 6455 specification and require both client and server implementations in a single library. It’s useful in environments where you must control low-level handshake details or integrate with legacy systems expecting precise protocol compliance. However, it lacks higher-level conveniences like automatic reconnection or message buffering, requiring more boilerplate code.
Choose ws if you want a fast, lightweight, and well-maintained WebSocket implementation that follows the standard closely while offering a clean, modern API. It’s the de facto choice for most real-time Node.js applications that don’t need Socket.IO’s extra features. It supports native compression, backpressure handling, and integrates smoothly with Express and other frameworks.
Socket.IO enables real-time bidirectional event-based communication. It consists of:
Some implementations in other languages are also available:
Its main features are:
Connections are established even in the presence of:
For this purpose, it relies on Engine.IO, which first establishes a long-polling connection, then tries to upgrade to better transports that are "tested" on the side, like WebSocket. Please see the Goals section for more information.
Unless instructed otherwise a disconnected client will try to reconnect forever, until the server is available again. Please see the available reconnection options here.
A heartbeat mechanism is implemented at the Engine.IO level, allowing both the server and the client to know when the other one is not responding anymore.
That functionality is achieved with timers set on both the server and the client, with timeout values (the pingInterval and pingTimeout parameters) shared during the connection handshake. Those timers require any subsequent client calls to be directed to the same server, hence the sticky-session requirement when using multiples nodes.
Any serializable data structures can be emitted, including:
Sample code:
io.on('connection', socket => {
socket.emit('request', /* … */); // emit an event to the socket
io.emit('broadcast', /* … */); // emit an event to all connected sockets
socket.on('reply', () => { /* … */ }); // listen to the event
});
Browser support is tested in Sauce Labs:
In order to create separation of concerns within your application (for example per module, or based on permissions), Socket.IO allows you to create several Namespaces, which will act as separate communication channels but will share the same underlying connection.
Within each Namespace, you can define arbitrary channels, called Rooms, that sockets can join and leave. You can then broadcast to any given room, reaching every socket that has joined it.
This is a useful feature to send notifications to a group of users, or to a given user connected on several devices for example.
Note: Socket.IO is not a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the ack id when a message acknowledgement is needed. 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 WebSocket server (like ws://echo.websocket.org) either. Please see the protocol specification here.
// with npm
npm install socket.io
// with yarn
yarn add socket.io
The following example attaches socket.io to a plain Node.JS
HTTP server listening on port 3000.
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('event', data => { /* … */ });
client.on('disconnect', () => { /* … */ });
});
server.listen(3000);
const io = require('socket.io')();
io.on('connection', client => { ... });
io.listen(3000);
import { Server } from "socket.io";
const io = new Server(server);
io.listen(3000);
Starting with 3.0, express applications have become request handler
functions that you pass to http or http Server instances. You need
to pass the Server to socket.io, not the express application
function. Also make sure to call .listen on the server, not the app.
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
Like Express.JS, Koa works by exposing an application as a request
handler function, but only by calling the callback method.
const app = require('koa')();
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
To integrate Socket.io in your Fastify application you just need to
register fastify-socket.io plugin. It will create a decorator
called io.
const app = require('fastify')();
app.register(require('fastify-socket.io'));
app.ready().then(() => {
app.io.on('connection', () => { /* … */ });
})
app.listen(3000);
Please see the documentation here.
The source code of the website can be found here. Contributions are welcome!
Socket.IO is powered by debug.
In order to see all the debug output, run your app with the environment variable
DEBUG including the desired scope.
To see the output from all of Socket.IO's debugging scopes you can use:
DEBUG=socket.io* node myapp
npm test
This runs the gulp task test. By default the test will be run with the source code in lib directory.
Set the environmental variable TEST_VERSION to compat to test the transpiled es5-compat version of the code.
The gulp task test will always transpile the source code into es5 and export to dist first before running the test.
Support us with a monthly donation and help us continue our activities. [Become a backer]
Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]