Socket.IO Client

4.8.3 · active · verified Sun Apr 19

Socket.IO Client is a JavaScript library designed for facilitating real-time, bidirectional, and event-based communication between web clients (browsers or Node.js applications) and a Socket.IO server. It abstracts away the complexities of WebSocket and HTTP long-polling, providing automatic fallback mechanisms, robust reconnection logic, and packet buffering to ensure reliable connectivity even in unstable network conditions. The current stable version, 4.8.3, is part of the actively developed Socket.IO v4 ecosystem. Releases are typically aligned with the server-side `socket.io` package, focusing on bug fixes, performance improvements, and dependency updates. Its key differentiators include its focus on cross-platform compatibility, simplified API for event handling, and built-in reliability features that make it a go-to choice for real-time applications requiring persistent connections.

Common errors

Warnings

Install

Imports

Quickstart

Establishes a connection to a Socket.IO server, sends a message upon connection, listens for incoming messages, and handles connection lifecycle events like disconnects and errors.

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

// Connect to a Socket.IO server running on localhost:3000
const socket: Socket = io('http://localhost:3000');

// Event listener for successful connection
socket.on('connect', () => {
  console.log(`Connected to the server with ID: ${socket.id}`);
  // Emit a 'greeting' event to the server
  socket.emit('greeting', 'Hello from the client!');
});

// Event listener for incoming 'message' events from the server
socket.on('message', (data: string) => {
  console.log('Received message:', data);
});

// Event listener for disconnection
socket.on('disconnect', (reason: Socket.DisconnectReason) => {
  console.log(`Disconnected from the server: ${reason}`);
});

// Event listener for connection errors
socket.on('connect_error', (error: Error) => {
  console.error('Connection error:', error.message);
});

// Manually disconnect after 15 seconds (optional)
setTimeout(() => {
  if (socket.connected) {
    console.log('Manually disconnecting after 15 seconds...');
    socket.disconnect();
  }
}, 15000);

view raw JSON →