Socket.io in Express

Sometimes HTTP isn't enough. For features like chat, live notifications, or collaborative editing, you need WebSockets. Socket.iois the most popular library for this in the Node/Express ecosystem.

1. Installation

npm install socket.io

2. Server Integration

Socket.io needs a raw HTTP server to attach to. We wrap the Express app.

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);

io.on('connection', (socket) => {
  console.log('A user connected');
  
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg); // Broadcast to everyone
  });
});

server.listen(3000);

3. Key Concepts

  • Emit: Sending a message.
  • On: Listening for a message.
  • Broadcast: Sending to everyone except the sender.
  • Rooms: Grouping sockets for private messaging.

4. Use Cases

  1. Real-time Dashboards.
  2. Collaborative Editors (like Google Docs).
  3. Instant Messengers.
  4. Live Binary Streaming.
Note: Socket.io is not just WebSockets; it provides fallback to long-polling for older browsers and automatically handles reconnection.