Script Valley
WebSockets & Real-Time Applications
Socket.IO for Production Real-Time AppsLesson 4.2

How to set up Socket.IO server and client

socket.io and socket.io-client installation, Server constructor with http, io.on connection, socket.emit, socket.on, client io() factory, connection event, CORS configuration

Socket.IO Server Setup

Install both packages:

npm install socket.io socket.io-client

Server with Express:

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: 'http://localhost:3000', methods: ['GET', 'POST'] } }); io.on('connection', (socket) => { console.log('Connected:', socket.id); socket.on('chat:message', (data) => { io.emit('chat:message', { ...data, from: socket.id }); }); socket.on('disconnect', (reason) => { console.log('Disconnected:', socket.id, reason); }); }); server.listen(3000);

Browser client:

import { io } from 'socket.io-client'; const socket = io('http://localhost:3000'); socket.on('connect', () => console.log('ID:', socket.id)); socket.emit('chat:message', { text: 'Hello' }); socket.on('chat:message', (data) => console.log(data));

CORS configuration is required when the client and server origins differ. Without it, the polling handshake (which uses HTTP) will be blocked.

Up next

How to use Socket.IO rooms and namespaces

Sign in to track progress