DEV Community

Alex Spinov
Alex Spinov

Posted on

Socket.io Has a Free Real-Time API That Handles Millions of Connections

Socket.IO provides real-time bidirectional communication with automatic reconnection, room management, and binary streaming — all with a clean API.

Server Setup

npm install socket.io
Enter fullscreen mode Exit fullscreen mode
import { Server } from 'socket.io';

const io = new Server(3000, {
  cors: { origin: '*' }
});

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

  socket.on('chat:message', (data) => {
    // Broadcast to everyone in the room
    io.to(data.room).emit('chat:message', {
      user: data.user,
      text: data.text,
      timestamp: Date.now()
    });
  });

  socket.on('join:room', (room) => {
    socket.join(room);
    socket.to(room).emit('user:joined', socket.id);
  });

  socket.on('disconnect', () => {
    console.log(`Disconnected: ${socket.id}`);
  });
});
Enter fullscreen mode Exit fullscreen mode

Client

import { io } from 'socket.io-client';

const socket = io('http://localhost:3000');

socket.emit('join:room', 'general');
socket.emit('chat:message', { room: 'general', user: 'Alice', text: 'Hello!' });

socket.on('chat:message', (msg) => {
  console.log(`${msg.user}: ${msg.text}`);
});
Enter fullscreen mode Exit fullscreen mode

Admin API

Socket.IO 4.x includes an admin namespace:

import { instrument } from '@socket.io/admin-ui';

instrument(io, { auth: false });
// Access dashboard at https://admin.socket.io
Enter fullscreen mode Exit fullscreen mode

Scaling with Redis

import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';

const pubClient = createClient({ url: 'redis://localhost:6379' });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);

io.adapter(createAdapter(pubClient, subClient));
Enter fullscreen mode Exit fullscreen mode

Why This Matters

  • Auto-reconnection: Handles network drops gracefully
  • Room management: Built-in pub/sub without external broker
  • Binary support: Stream files, images, audio in real-time
  • Scalable: Redis adapter for multi-server deployments

Need custom real-time tools or WebSocket infrastructure? I build developer tools and data pipelines. Check out my web scraping actors on Apify or reach out at spinov001@gmail.com for custom solutions.

Top comments (0)