Real-time features — live notifications, collaborative editing, multiplayer interactions — require a persistent, low-latency connection between client and server. Socket.io makes this straightforward to implement.
Why Not Plain WebSockets?
WebSockets provide the raw connection, but Socket.io adds:
- Automatic reconnection with exponential backoff
- Room and namespace support for organizing connections
- Fallback to HTTP long-polling when WebSockets are unavailable
- Event-based API that is cleaner than raw message passing
Basic Setup
Server (Node.js):
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {
cors: { origin: "*" }
});
io.on("connection", (socket) => {
console.log("client connected:", socket.id);
socket.on("message", (data) => {
// Broadcast to all other clients
socket.broadcast.emit("message", data);
});
socket.on("disconnect", () => {
console.log("client disconnected:", socket.id);
});
});
httpServer.listen(3000);
Client (browser):
import { io } from "socket.io-client";
const socket = io("http://localhost:3000");
socket.on("connect", () => {
console.log("connected as", socket.id);
});
socket.emit("message", { text: "Hello, world!" });
socket.on("message", (data) => {
console.log("received:", data);
});
Rooms — Scoping Messages
Rooms let you send events to a subset of connected clients:
// Server: join a room
socket.join("room-alpha");
// Server: emit only to that room
io.to("room-alpha").emit("update", payload);
This is the foundation for features like per-channel chat or per-document collaboration.
Key Takeaway
Socket.io abstracts away the complexity of real-time networking. Start with a simple chat app to understand the event loop, then layer in rooms and authentication as your use case grows.