WebSocket Libraries for Node.js: ws, Socket.IO and µWebSockets
WebSocket is a protocol that provides a persistent bidirectional connection between a client and a server. In the Node.js ecosystem, there are several popular libraries implementing this protocol. In this article, we will look at three main ones: ws, Socket.IO and µWebSockets (uWS). You will learn how to install them, write a simple chat server, and choose the right tool for your task.
1. ws Library — Lightweight and High-Performance
ws is the most popular and fastest WebSocket library for Node.js. It implements the pure WebSocket protocol without any additional overhead, providing minimal overhead and maximum speed.
Installation
npm install wsExample: Echo Server
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws) => { console.log('Client connected');
ws.on('message', (message) => { console.log(`Received: ${message}`); ws.send(`Echo: ${message}`); });
ws.on('close', () => { console.log('Client disconnected'); });});
console.log('WebSocket server started on ws://localhost:8080');Client Side (Browser)
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => { console.log('Connection established'); socket.send('Hello, server!');};
socket.onmessage = (event) => { console.log('Response from server:', event.data);};
socket.onerror = (error) => { console.error('WebSocket error:', error);};ws Features:
- Performance: 2-3 times faster than Socket.IO in throughput tests.
- Minimalism: No built-in reconnection mechanisms, rooms, or fallback transports.
- Support: Full compatibility with RFC 6455.
- Use case: Ideal for real-time applications where speed is critical (stock market data, games, high-load chats).
2. Socket.IO — Convenience and Reliability for Production
Socket.IO is not just a WebSocket library, but a full framework for real-time applications. It adds on top of WebSocket: automatic reconnection, rooms, namespaces, fallback to long-polling (if WebSocket is not supported), and a convenient API.
Installation
npm install socket.ioExample: Simple Chat Server
const http = require('http');const { Server } = require('socket.io');
const server = http.createServer();const io = new Server(server, { cors: { origin: '*' }});
io.on('connection', (socket) => { console.log(`User connected: ${socket.id}`);
socket.on('chat message', (msg) => { console.log(`Message: ${msg}`); io.emit('chat message', msg); // broadcast to all });
socket.on('disconnect', () => { console.log(`User disconnected: ${socket.id}`); });});
server.listen(3000, () => { console.log('Socket.IO server on http://localhost:3000');});Client Side (Browser)
<script src="/socket.io/socket.io.js"></script><script> const socket = io('http://localhost:3000');
socket.on('connect', () => { console.log('Connected to server'); socket.emit('chat message', 'Hello everyone!'); });
socket.on('chat message', (msg) => { const item = document.createElement('li'); item.textContent = msg; document.getElementById('messages').appendChild(item); });</script>Socket.IO Features:
- Automatic Reconnection: When the connection is lost, the client automatically tries to re-establish it.
Also in library
Recommendations