TL;DR
Socket.IO enables real-time, bidirectional communication between web clients and servers. It's free, open-source, and handles WebSocket connections with automatic fallbacks, reconnection, and room-based broadcasting.
What Is Socket.IO?
Socket.IO is the most popular real-time engine for the web:
- Bidirectional — server can push to clients, clients can push to server
- Auto-reconnection — handles disconnects gracefully
- Rooms and namespaces — organize connections logically
- Binary support — send files, images, audio in real-time
- Multiplexing — multiple channels over a single connection
- Works everywhere — WebSocket with HTTP long-polling fallback
Quick Start
Server (Node.js)
import { Server } from "socket.io";
const io = new Server(3000, {
cors: { origin: "*" },
});
io.on("connection", (socket) => {
console.log(`User connected: ${socket.id}`);
// Listen for messages
socket.on("chat:message", (data) => {
// Broadcast to all other clients
socket.broadcast.emit("chat:message", {
user: data.user,
text: data.text,
timestamp: Date.now(),
});
});
// Join a room
socket.on("room:join", (roomName) => {
socket.join(roomName);
io.to(roomName).emit("room:user-joined", socket.id);
});
socket.on("disconnect", () => {
console.log(`User disconnected: ${socket.id}`);
});
});
Client (Browser)
import { io } from "socket.io-client";
const socket = io("http://localhost:3000");
socket.on("connect", () => {
console.log("Connected!", socket.id);
});
// Send a message
socket.emit("chat:message", {
user: "Alice",
text: "Hello everyone!",
});
// Receive messages
socket.on("chat:message", (data) => {
console.log(`${data.user}: ${data.text}`);
});
// Join a room
socket.emit("room:join", "developers");
Advanced Patterns
Acknowledgements (Request-Response)
// Server
socket.on("order:create", (orderData, callback) => {
const order = await createOrder(orderData);
callback({ status: "ok", orderId: order.id });
});
// Client
socket.emit("order:create", { item: "Pizza" }, (response) => {
console.log(`Order created: ${response.orderId}`);
});
Middleware
// Authentication middleware
io.use((socket, next) => {
const token = socket.handshake.auth.token;
try {
const user = verifyJWT(token);
socket.data.user = user;
next();
} catch (err) {
next(new Error("Authentication failed"));
}
});
Scaling with Redis Adapter
import { createAdapter } from "@socket.io/redis-adapter";
import { createClient } from "redis";
const pubClient = createClient({ url: "redis://localhost:6379" });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);
io.adapter(createAdapter(pubClient, subClient));
// Now Socket.IO works across multiple server instances!
Socket.IO vs Alternatives
| Feature | Socket.IO | ws | PartyKit | Pusher |
|---|---|---|---|---|
| Price | Free | Free | Free tier | Freemium |
| Auto-reconnect | ✅ | ❌ | ✅ | ✅ |
| Rooms | ✅ | ❌ | ✅ | ✅ |
| Binary data | ✅ | ✅ | ✅ | ❌ |
| Scaling | Redis adapter | Manual | Built-in | Managed |
| Fallback transport | ✅ | ❌ | ❌ | ✅ |
Use Cases
- Chat applications — real-time messaging with rooms
- Live dashboards — push data updates to clients
- Collaborative editing — Google Docs-style real-time sync
- Gaming — multiplayer game state synchronization
- IoT — device-to-server communication
- Live notifications — instant push to connected users
Resources
- Socket.IO Documentation
- GitHub Repository — 62K+ stars
- Socket.IO Admin UI
Need real-time web data for your Socket.IO app? My Apify scraping tools extract live data from any website — perfect for powering real-time dashboards. Questions? Email spinov001@gmail.com
Top comments (0)