Day 02 Core Concepts

Socket.io Basics

Server setup, emitting events, client connections, namespaces. Part of the free WebSockets in 5 Days course at Precision AI Academy.

~1 hour Hands-on Precision AI Academy

Today's Objective

Namespaces let you create separate communication channels on the same server.

01

Why Socket.io Instead of Raw WebSockets?

Raw WebSockets are powerful but minimal — you get a message channel and that's it. Socket.io adds rooms, namespaces, automatic reconnection, event names, and fallback to HTTP long-polling when WebSockets aren't available. For most real-time apps, Socket.io is the right choice.

💡
Socket.io vs raw WebSockets: Use raw ws when you need the lowest latency and smallest payload (gaming, IoT). Use Socket.io for app-level features: chat, notifications, live updates.
02

Setting Up a Socket.io Server

server.js — Socket.io Setup
server.js — Socket.io Setup
const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: { origin: '*' } // Configure properly in production
});

io.on('connection', (socket) => {
  console.log('User connected:', socket.id);

  // Listen for a 'message' event from the client
  socket.on('message', (data) => {
    console.log('Message from', socket.id, ':', data);
    // Emit back to everyone including sender
    io.emit('message', { from: socket.id, text: data });
  });

  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

httpServer.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
03

Emitting Events

Socket.io uses named events rather than raw messages. This makes your code much easier to read and maintain. There are four main ways to emit:

Emit Patterns
Emit Patterns
// To the sender only
socket.emit('event', data);

// To everyone except the sender
socket.broadcast.emit('event', data);

// To everyone including sender
io.emit('event', data);

// To a specific room
io.to('room-name').emit('event', data);
04

Namespaces

Namespaces let you create separate communication channels on the same server. Each namespace has its own event handlers and rooms — useful for separating admin traffic from user traffic or building multi-tenant apps.

Namespaces
Namespaces
// Server: create a namespace
const adminNS = io.of('/admin');
adminNS.on('connection', (socket) => {
  socket.emit('welcome', 'You are in the admin namespace');
});

// Client: connect to a namespace
const adminSocket = io('/admin');
adminSocket.on('welcome', (msg) => console.log(msg));

Supporting References & Reading

Go deeper with these external resources.

Docs
Socket.io Basics Official documentation for websockets.
GitHub
Socket.io Basics Open source examples and projects for Socket.io Basics
MDN
MDN Web Docs Comprehensive web technology reference

Day 2 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 3
Day 3 of the WebSockets in 5 Days course