Socket.IO

4.8.3 · active · verified Sat Apr 18

Socket.IO is a real-time, bidirectional, event-based communication library that enables low-latency communication between web clients and Node.js servers. It facilitates cross-browser messaging with fallback options for reliable connections, even through proxies and firewalls. The current stable version is 4.8.3, and the package receives regular patch releases for bug fixes, security updates, and dependency maintenance across its ecosystem components.

Common errors

Warnings

Install

Imports

Quickstart

This code sets up a basic Socket.IO server on port 3000 that listens for client connections. When a client connects, it logs the ID, sends a 'hello' event, listens for 'message' events from that client, and broadcasts them to all connected clients. It also handles client disconnections.

import { Server } from 'socket.io';
import { createServer } from 'http';

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: {
    origin: '*', // Allow all origins for simplicity in quickstart
    methods: ['GET', 'POST']
  }
});

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

  socket.emit('hello', `Welcome, ${socket.id}!`);

  socket.on('message', (payload: string) => {
    console.log(`Received message from ${socket.id}: ${payload}`);
    // Broadcast the message to all connected clients
    io.emit('broadcast', `Message from ${socket.id}: ${payload}`);
  });

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

const PORT = process.env.PORT ?? 3000;
httpServer.listen(PORT, () => {
  console.log(`Socket.IO server listening on port ${PORT}`);
});

view raw JSON →