Skip to content

WebSocket and Socket.IO — Complete Guide to Real-Time Communication

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Websocket and Socket.IO. We cover key concepts, practical examples, and best practices to help you master this topic.

WebSocket and Socket.IO provide full-duplex communication channels over TCP, enabling real-time features like chat, live notifications, and collaborative editing.

What You'll Learn

By the end of this tutorial, you'll set up Socket.IO with Express, emit and handle events, use rooms for grouping, broadcast messages, authenticate connections, and build real-time features.

Why WebSocket Matters

HTTP is request-response. The server can't send data to the client without a request. WebSocket maintains a persistent connection where both sides can send data anytime, essential for real-time apps.

Real-World Use

A live dashboard uses WebSocket to push real-time metrics to browsers. When a new order comes in, the server emits an event and all connected dashboards update instantly without polling.

WebSocket Learning Path

flowchart LR
  A[GraphQL API] --> B[WebSocket]
  B --> C[Realtime Apps]
  C --> D[Authentication]
  D --> E[Authorization]
  A --> F{You Are Here}
  style F fill:#f90,color:#fff

Socket.IO Server Setup

npm install socket.io
import express from "express";
import { createServer } from "node:http";
import { Server } from "socket.io";
const app = express();
const server = createServer(app);
const io = new Server(server, {
  cors: { origin: "http://localhost:3000", methods: ["GET", "POST"] }
});
io.on("connection", (socket) => {
  console.log(`User connected: ${socket.id}`);
  socket.on("disconnect", () => console.log(`User disconnected: ${socket.id}`));
});
server.listen(4000, () => console.log("Server on port 4000"));

Client Connection

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io("http://localhost:4000");
  socket.on("connect", () => console.log("Connected:", socket.id));
</script>

Emitting and Handling Events

// Server
io.on("connection", (socket) => {
  socket.on("chat message", (msg) => {
    console.log("Message:", msg);
    io.emit("chat message", msg);  // Broadcast to all
  });
  socket.emit("welcome", "Welcome to the chat!");
});

// Client
socket.emit("chat message", "Hello everyone!");
socket.on("welcome", (msg) => console.log(msg));

Rooms

Rooms group sockets for targeted broadcasting.

socket.join("room-1");  // Join a room
socket.to("room-1").emit("message", "Sent to room only");
io.to("room-1").emit("message", "Broadcast to room");

Broadcasting

// To all connected clients
io.emit("broadcast", "Everyone gets this");
// To all except sender
socket.broadcast.emit("broadcast", "Everyone except sender");
// To all in room except sender
socket.to("room-1").emit("message", "Room except sender");

Authentication

io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  if (!token) return next(new Error("Authentication required"));
  try {
    const user = verifyToken(token);
    socket.user = user;
    next();
  } catch (err) {
    next(new Error("Invalid token"));
  }
});
io.on("connection", (socket) => {
  console.log(`Authenticated user: ${socket.user.name}`);
});

Common Mistakes

1. Forgetting CORS Configuration

Socket.IO requests are cross-origin by default. Configure cors option in the Server constructor.

2. Emitting to Wrong Recipient

socket.emit sends to the socket itself. socket.broadcast.emit sends to all others. io.emit sends to all. Know the difference.

3. Not Handling Disconnect Cleanup

When a user disconnects, clean up their state: remove from rooms, update user lists, notify others.

4. Sending Too Much Data

WebSocket messages are not compressed. Large payloads slow down real-time features. Keep messages small.

5. No Reconnection Strategy

Socket.IO has built-in reconnection, but test it. Handle stale state after reconnection.

Practice Questions

1. What is the difference between HTTP and WebSocket?

HTTP is request-response (client initiates). WebSocket is bidirectional (both sides send data anytime after connection).

2. What is a Socket.IO room?

A room is a channel that sockets can join. Messages sent to a room go to all sockets in that room.

3. How do you authenticate a WebSocket connection?

Pass a token in the handshake auth option. Validate it in the io.use() middleware before allowing the connection.

4. What is broadcasting in Socket.IO?

Sending a message to all connected clients (io.emit) or all except the sender (socket.broadcast.emit).

5. Challenge: Create a simple chat server with rooms using Socket.IO.

const io = new Server(server);
io.on("connection", (socket) => {
  socket.on("join room", (room) => socket.join(room));
  socket.on("chat message", ({ room, msg }) => {
    io.to(room).emit("chat message", { user: socket.id, msg });
  });
});

FAQ

What is the difference between WebSocket and Socket.IO?

WebSocket is the protocol. Socket.IO is a library that adds rooms, namespaces, auto-reconnection, and fallback transports.

Does Socket.IO work without WebSocket?

Yes. Socket.IO falls back to HTTP long-polling when WebSocket is unavailable.

How do I scale Socket.IO across multiple servers?

Use a Redis adapter (@socket.io/redis-adapter) to broadcast events across processes.

What is a Socket.IO namespace?

Namespaces let you create separate communication channels on the same server: io.of('/admin'), io.of('/chat').

How do I send binary data over Socket.IO?

Socket.IO supports Buffer, ArrayBuffer, and Blob. Emit them directly: socket.emit('file', buffer).

Mini Project: Live Notification System

Build a real-time notification system using Socket.IO.

import { Server } from "socket.io";
import { createServer } from "node:http";
const server = createServer();
const io = new Server(server);
io.use((socket, next) => {
  socket.userId = socket.handshake.auth.userId;
  next();
});
io.on("connection", (socket) => {
  socket.join(`user:${socket.userId}`);
  socket.emit("notification", { type: "welcome", message: "Connected!" });
});
function sendNotification(userId, notification) {
  io.to(`user:${userId}`).emit("notification", notification);
}
setInterval(() => {
  sendNotification("user-1", { type: "update", message: "New data available", time: Date.now() });
}, 5000);
server.listen(4000);

What's Next

Realtime Apps Node.js Authentication Node.js File Upload

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro