WebSockets enable full‑duplex, real‑time communication between client and
server. This tutorial covers the WebSocket protocol and Socket.io — the
most popular real‑time library for Node.js. You'll learn to emit and
listen to events, use rooms and namespaces, and broadcast messages.
Why this matters:
Real‑time features (chat, notifications, live updates, collaborative tools)
are essential for modern applications. WebSockets make these possible
with low latency and high efficiency.
1. WebSocket Protocol
WebSocket is a protocol that provides a persistent, bidirectional
communication channel over a single TCP connection.
HTTP upgrade: Starts with an HTTP request, then upgrades to WebSocket.
Full‑duplex: Both client and server can send messages at any time.
Low latency: No HTTP headers overhead after connection.
Use cases: Chat, gaming, live sports, financial tickers, collaborative
editing.
Event naming: Use meaningful names (e.g., 'chat:message',
'user:joined', 'notification:new').
4. Rooms & Namespaces
Rooms
Rooms allow you to send messages to a subset of connected clients.
// Server – join a room
socket.on('joinRoom', (roomId) => {
socket.join(roomId);
socket.to(roomId).emit('userJoined', {
userId: socket.id,
roomId
});
});
// Send message to a room
socket.on('roomMessage', ({ roomId, message }) => {
io.to(roomId).emit('roomMessage', {
userId: socket.id,
message,
timestamp: new Date()
});
});
// Leave a room
socket.on('leaveRoom', (roomId) => {
socket.leave(roomId);
});
Namespaces
Namespaces separate communication channels (e.g., /chat,
/notifications).
// Server – define a namespace
const chatNamespace = io.of('/chat');
chatNamespace.on('connection', (socket) => {
// Handles only connections to /chat
});
// Client – connect to a namespace
const chatSocket = io('/chat');
5. Broadcasting
Broadcasting sends a message to all clients except the sender.
// Server – broadcast to all except sender
socket.broadcast.emit('userTyping', { userId: socket.id });
// Broadcast to all clients in a room (except sender)
socket.broadcast.to('room-123').emit('message', data);
// Broadcast to all clients globally (including sender)
io.emit('systemNotification', { message: 'Maintenance in 5 minutes' });
// Broadcast to all clients in a namespace (except sender)
chatNamespace.to(roomId).emit('newMessage', data);
Implement a simple chat application using Socket.io with: (1) Multiple
rooms, (2) User join/leave notifications, (3) Typing indicators, (4) Message history (last
50 messages).
Sample outline
Server: Socket.io server with rooms, message storage
(in‑memory).
Client: React chat UI with room selection, message list, and
message input.
Features: Join room, leave room, typing indicator, message
history.
Mini‑Project
Real‑Time Dashboard
Build a real‑time dashboard that displays live data:
Server emits 'update' events every second with random data (e.g., stock prices, sensor
readings)
Client receives updates and renders charts (using Chart.js or Recharts)
Multiple clients can connect and receive the same data
Add a filter to show/hide specific data streams
Sample outline
Server: Socket.io server that emits random data points for 3
different sensors.
Client: React app with real‑time charts (Recharts) that update
every second.
Controls: Toggle buttons to show/hide specific data streams.
History: Store last 30 data points per stream.
Tutorial Summary
You learned the fundamentals of real‑time communication using WebSockets
and Socket.io. You covered event handling, rooms, namespaces, broadcasting,
and built a foundation for real‑time applications. These skills are
essential for modern, interactive applications.
Key takeaway: Socket.io makes real‑time communication
accessible and reliable. Use rooms and namespaces to organise your
application's real‑time features.