100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Your First Socket.IO Server

A hands-on walkthrough of building and running a minimal Socket.IO server with Express, handling connections, custom events, and disconnections.

FoundationsBeginner9 min readJul 10, 2026
Analogies

Your First Socket.IO Server

Building your first Socket.IO server involves three pieces: an HTTP server (usually via Express), a Socket.IO server instance attached to it, and event handlers registered inside the 'connection' event, which fires once per client that successfully connects. Every connected client is represented server-side as a 'socket' object with a unique 'id', and all event listeners you attach for that client -- custom events, 'disconnect', errors -- go inside that connection callback.

🏏

Cricket analogy: It's like a stadium's turnstile system logging each fan's entry with a unique ticket ID the moment they walk in, similar to how the 'connection' event fires once per client with a unique socket.id.

Setting Up the Server

Start by creating an Express app and wrapping it with Node's http.createServer, since Socket.IO needs the raw HTTP server object (not the Express app directly) to attach its upgrade handler. Then instantiate 'new Server(httpServer, options)', configuring CORS if your frontend runs on a different port during development. Finally, call httpServer.listen(port) -- not app.listen(port) -- so both regular HTTP routes and Socket.IO's WebSocket upgrade requests are served from the same underlying server.

🏏

Cricket analogy: It's like routing both the TV broadcast feed and the radio commentary feed through the same central production truck rather than two separate trucks, similar to httpServer.listen() serving both HTTP and Socket.IO traffic.

javascript
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const httpServer = http.createServer(app);
const io = new Server(httpServer, {
  cors: { origin: 'http://localhost:5173', methods: ['GET', 'POST'] },
});

app.get('/health', (req, res) => res.send('ok'));

io.on('connection', (socket) => {
  console.log(`Client connected: ${socket.id}`);

  socket.on('joinRoom', (roomName) => {
    socket.join(roomName);
    io.to(roomName).emit('systemMessage', `${socket.id} joined ${roomName}`);
  });

  socket.on('disconnect', (reason) => {
    console.log(`Client disconnected: ${socket.id}, reason: ${reason}`);
  });
});

httpServer.listen(3000, () => console.log('Listening on port 3000'));

Handling Connections and Custom Events

Inside the 'connection' callback, use socket.on(eventName, handler) to react to events the client emits, and socket.emit(eventName, data) to send data back to just that one client. To send to everyone, use io.emit(...); to send to everyone except the sender, use socket.broadcast.emit(...); to target a subset, use socket.join(roomName) followed by io.to(roomName).emit(...). Always register a 'disconnect' listener too, since cleaning up any per-client state (like removing them from an in-memory room list) typically needs to happen there.

🏏

Cricket analogy: It's like a stadium PA distinguishing between a message to one specific box (socket.emit), an announcement to the whole crowd (io.emit), and an announcement to everyone except the person who just reported the issue (socket.broadcast.emit).

Forgetting to configure CORS correctly is one of the most common first-server mistakes: if your frontend runs on a different origin (e.g., localhost:5173) than your Socket.IO server (e.g., localhost:3000), you must set the 'cors' option in 'new Server(httpServer, { cors: { origin: ... } })', or the browser will block the connection.

  • A Socket.IO server needs an HTTP server instance, a Server object attached to it, and 'connection' event handlers.
  • Call httpServer.listen(), not app.listen(), so both HTTP and Socket.IO traffic share the same server.
  • Each connected client gets a unique socket.id and its own socket object inside the 'connection' callback.
  • Use socket.emit for one client, io.emit for everyone, socket.broadcast.emit for everyone except the sender, and rooms for targeted subsets.
  • Always handle 'disconnect' to clean up any per-client state.
  • Configure the 'cors' option whenever frontend and backend run on different origins.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#SocketIOStudyNotes#YourFirstSocketIOServer#Socket#Server#Setting#Handling#Networking#StudyNotes#SkillVeris