tezvyn:

How to add Socket.IO to an Express application?

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

basic Socket.IO setup and HTTP server integration.

OUTLINE

Create HTTP server with express(), attach Socket.IO to it, listen on server not app, define event handlers.

THE HTTP SERVER LAYER

Socket.IO requires a raw HTTP server to upgrade connections to WebSocket. Express provides app.listen() which internally creates an HTTP server, but Socket.IO needs access to that server object. The pattern is to explicitly create an HTTP server wrapping Express, then pass that server to Socket.IO.

BASIC SETUP STEPS

First, create an HTTP server: const http = require('http'); const server = http.createServer(app);. Then initialize Socket.IO: const io = require('socket.io')(server);. Now attach handlers: io.on('connection', (socket) => { ... });. Finally, start listening: server.listen(3000);. This differs from app.listen() because app.listen() hides the server object.

CONNECTION EVENT HANDLER

When a client connects, the 'connection' event fires with a socket object. Inside the handler, define what happens: io.on('connection', (socket) => { console.log('User connected:', socket.id); socket.on('message', (data) => { ... }); socket.on('disconnect', () => { ... }); });. Each socket is one client. Disconnections clean up automatically.

SENDING MESSAGES TO CLIENTS

Within the connection handler, use socket.emit() or socket.broadcast.emit(). For example, when a client sends 'message', the server receives it via socket.on('message', callback) and can respond or broadcast: socket.broadcast.emit('newMessage', data);. This notifies all other clients.

COMMON MISTAKE

New developers often call app.listen(3000) and try to attach Socket.IO afterward. This doesn't work because the server object is hidden. The fix is always: wrap app in http.createServer(app) before Socket.IO initialization. Alternatively, some use app.listen() and pass app._server to Socket.IO, but this is unreliable and not recommended.

Read the original → socket.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.