Websocket Socketio
title: "Socket.IO" description: "Learn how to use Socket.IO for real-time bidirectional communication with features like rooms, namespaces, auto-reconnection, and fallback transports." weight: 16 date: 2026-06-28 lastmod: 2026-06-28 tags: ["apis", "websocket"]
Socket.IO is a library that builds on WebSocket with additional features: auto-reconnection, fallback transports, rooms, namespaces, and multiplexing. It simplifies real-time application development.
## What You'll Learn
- Socket.IO vs raw WebSocket
- Setting up Socket.IO server and client
- Events and acknowledgments
- Broadcasting and rooms
- Fallback transport mechanism
## Why It Matters
Socket.IO handles many WebSocket pain points automatically: reconnection, scaling, and transport negotiation. It reduces boilerplate code and provides a higher-level API for real-time applications.
## Real-World Use
A collaborative document editor uses Socket.IO for real-time editing. It uses rooms for document-specific channels, namespaces for separating editing from chat, and built-in reconnection for handling network interruptions.
## Flow Chart
```mermaid
flowchart LR
A[Socket.IO Client] --> B{Transport}
B -->|WebSocket| C[Direct Connection]
B -->|Polling| D[HTTP Long-Polling]
B -->|WebTransport| E[Experimental]
C --> F[Socket.IO Server]
D --> F
E --> F
F --> G[Rooms]
F --> H[Namespaces]
F --> I[Broadcast]
Code Examples
Example 1: Socket.IO Server Setup
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: 'https://app.example.com',
methods: ['GET', 'POST'],
},
pingInterval: 25000,
pingTimeout: 20000,
});
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
socket.on('message', (data) => {
console.log('Message:', data);
socket.emit('message', { text: 'Message received', id: data.id });
});
socket.on('disconnect', (reason) => {
console.log('Client disconnected:', socket.id, reason);
});
});
server.listen(3000, () => {
console.log('Socket.IO server on port 3000');
});
Expected output: Socket.IO server running with CORS configuration and event handling.
Example 2: Socket.IO Client with Events
const { io } = require('socket.io-client');
const socket = io('https://server.example.com', {
transports: ['websocket', 'polling'],
auth: {
token: 'jwt-token-here',
},
});
socket.on('connect', () => {
console.log('Connected with ID:', socket.id);
socket.emit('message', {
id: 1,
text: 'Hello Socket.IO',
});
});
socket.on('message', (data) => {
console.log('Server response:', data);
});
socket.on('disconnect', (reason) => {
console.log('Disconnected:', reason);
});
socket.on('connect_error', (error) => {
console.error('Connection error:', error.message);
});
Expected output: Client connects to Socket.IO server, sends and receives messages with event-based communication.
Example 3: Rooms and Broadcasting
const { Server } = require('socket.io');
const io = new Server(3000);
io.on('connection', (socket) => {
// Join room
socket.on('join-room', (roomName) => {
socket.join(roomName);
io.to(roomName).emit('notification', {
text: `${socket.id} joined ${roomName}`,
});
});
// Leave room
socket.on('leave-room', (roomName) => {
socket.leave(roomName);
});
// Send to room
socket.on('room-message', ({ room, message }) => {
io.to(room).emit('room-message', {
sender: socket.id,
text: message,
});
});
// Broadcast to all except sender
socket.on('broadcast', (data) => {
socket.broadcast.emit('broadcast', data);
});
// Send to specific socket
socket.on('private-message', ({ to, message }) => {
io.to(to).emit('private-message', {
from: socket.id,
text: message,
});
});
});
Expected output: Clients can join/leave rooms, send messages to specific rooms, broadcast to all, and send private messages to specific sockets.
Common Mistakes
| Mistake | Explanation |
|---|---|
| Using Socket.IO on both ends | If the client uses raw WebSocket, it cannot connect to a Socket.IO server and vice versa |
| Not configuring CORS | Socket.IO requires explicit CORS configuration for browser clients from different origins |
| Forgetting to handle disconnections | Always implement disconnection handlers for cleanup and state management |
| Overusing broadcast | Broadcasting to all clients can overwhelm connections; use targeted rooms |
| Ignoring transport fallback | Socket.IO falls back to polling when WebSocket fails; this affects latency and scalability |
Practice Questions
- What features does Socket.IO add beyond raw WebSocket?
- How do Socket.IO rooms work?
- What is the difference between rooms and namespaces?
- How does Socket.IO handle reconnection?
- What are Socket.IO acknowledgments and when would you use them?
Challenge
Build a Socket.IO-based collaboration feature for a document editor. Implement rooms per document, cursor position sharing, real-time text updates, and presence indicators showing which users are viewing each document.
FAQ
Mini Project
Build a real-time collaborative whiteboard with Socket.IO. Multiple users can draw on the same canvas, see each others' cursors, chat in a side panel, and join/leave rooms for different whiteboards. Include user presence indicators.
What's Next
Learn about WebSocket rooms and namespaces patterns
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro