WebSockets & Socket.io - Real-Time Bidirectional Full-Duplex Communication

Traditional HTTP requests require the browser to constantly poll the server for updates. For real-time applications—such as live multiplayer gaming, financial stock tickers, collaborative document editing, and chat platforms—WebSockets provide a persistent, two-way connection where the server can push updates instantly.

Building a Real-Time Chat Server with Socket.io

npm install express socket.io
// socketServer.js
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: '*' } // Allow cross-origin client connections
});

io.on('connection', (socket) => {
  console.log(`[USER CONNECTED] Socket ID: ${socket.id}`);

  // 1. Join a specific chat room
  socket.on('joinRoom', (roomName) => {
    socket.join(roomName);
    console.log(`Socket ${socket.id} joined room: ${roomName}`);

    // Notify room members
    socket.to(roomName).emit('notification', `New student entered ${roomName}!`);
  });

  // 2. Handle incoming room message
  socket.on('chatMessage', ({ room, user, message }) => {
    console.log(`[${room}] ${user}: ${message}`);

    // Broadcast message to everyone in room including sender
    io.to(room).emit('newChatMessage', {
      user,
      message,
      time: new Date().toLocaleTimeString()
    });
  });

  // 3. Handle disconnect
  socket.on('disconnect', () => {
    console.log(`[USER DISCONNECTED] Socket ID: ${socket.id}`);
  });
});

server.listen(3000, () => console.log('Socket.io server running on port 3000'));

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between HTTP and WebSockets?

HTTP is a stateless, half-duplex request-response protocol where the client must always initiate communication and each request carries heavy header overhead. WebSockets establish an open, persistent, bi-directional, full-duplex TCP connection over a single socket, allowing the server to push real-time events to clients with minimal framing overhead (2 bytes).

Q2. What is Socket.io and why use it over native WebSockets (ws)?

Socket.io is a library that wraps WebSockets with automatic reconnection, heartbeat fallback to HTTP long-polling (if firewalls block WebSockets), rooms, namespaces, and binary streaming support out-of-the-box.

Q3. What are Rooms in Socket.io?

Rooms are server-only channels that sockets can join (socket.join('room-name')) and leave. Broadcasting to a room (io.to('room-name').emit()) delivers messages exclusively to users subscribed to that specific chat or document.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

HTTP Web Server

WebSockets handshake initiates via an HTTP Upgrade header.

Redis In-Memory Caching

Scale Socket.io across servers with the Redis Adapter.

JWT Authentication

Authenticate WebSocket connections during handshake.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!