WebSocket with Node.js (ws and Socket.IO)
In this tutorial, you will learn about Websocket with Node.js (ws and Socket.IO). We cover key concepts, practical examples, and best practices to help you master this topic.
Node.js is the most popular platform for WebSocket servers. The ws library provides a lightweight WebSocket implementation. Socket.IO adds conventions, rooms, namespaces, auto-reconnection, and HTTP long-polling fallback on top of WebSocket.
What You'll Learn
- Server and client setup with the ws library
- Message handling and broadcasting patterns
- Socket.IO features: rooms, namespaces, events
- Socket.IO fallback transport options
- Choosing between ws and Socket.IO
Why It Matters
The ws library is ideal for custom WebSocket protocols. Socket.IO is better for rapid application development with built-in reconnection and room management.
Real-World Use
Discord uses a custom protocol over WebSocket (similar to ws library). Slack uses a Socket.IO-like abstraction. Many real-time apps use Socket.IO for its simplicity and reliability.
flowchart LR
subgraph ws [ws Library]
WServer[ws.Server] -->|raw WebSocket| WClient[ws client]
end
subgraph SocketIO [Socket.IO]
IOServer[Socket.IO Server] -->|WebSocket or HTTP Polling| IOClient[Socket.IO Client]
IOServer --> Rooms[Rooms]
IOServer --> Namespaces[Namespaces]
IOServer --> Events[Event-based Messaging]
end
Teacher Mindset
Use ws when you need full control over the WebSocket protocol. Use Socket.IO when you want built-in reconnection, rooms, and event-based messaging without reinventing the wheel.
Code Examples
// Example 1: ws library server
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws) => {
ws.on('message', (data) => {
const message = JSON.parse(data);
// Broadcast to all connected clients
server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
});
});
// Example 2: Socket.IO server
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: '*' }
});
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('chat message', (msg) => {
// Broadcast to all clients in the room
io.to(msg.room).emit('chat message', {
user: socket.id,
text: msg.text
});
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
server.listen(3000);
// Example 3: Socket.IO client
const io = require('socket.io-client');
const socket = io('http://localhost:3000', {
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000
});
socket.on('connect', () => {
console.log('Connected with ID:', socket.id);
socket.emit('chat message', { room: 'general', text: 'Hello!' });
});
socket.on('chat message', (msg) => {
console.log(`${msg.user}: ${msg.text}`);
});
socket.on('disconnect', () => console.log('Disconnected'));
Common Mistakes
- Using ws without handling the binary/text mode flag
- Broadcasting to all clients including the sender when sender exclusion is needed
- Not configuring Socket.IO CORS settings correctly
- Relying on Socket.IO auto-reconnection without fallback transport testing
- Using native WebSocket when Socket.IO client is expected (and vice versa)
Practice
- Build a chat server with the ws library that broadcasts messages.
- Implement the same chat server with Socket.IO including rooms.
- Add Socket.IO namespaces for admin and user channels.
- Test Socket.IO fallback by disabling WebSocket transport.
- Challenge: Build a presence system that tracks online users using both ws and Socket.IO.
FAQ
Mini Project
Build a real-time dashboard using Socket.IO. Create a server that emits random metrics every second. Create a client that displays the metrics in real-time. Add a namespace for admin metrics.
What's Next
Next, you will learn about rooms and namespaces for organizing WebSocket connections.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro