socket.io

The Socket.IO API provides robust tools for managing real-time, bidirectional communication between clients and servers. It includes a SocketManager for handling multiple namespaces and a SocketIOClient for individual socket connections. This document provides an overview of the API, including setup, configuration, and usage.


Getting Started

The Socket.IO API allows you to create and manage WebSocket connections using a SocketManager. Each SocketManager can handle multiple namespaces and configurations.

Example:

1// Create a SocketManager instance
2const manager = new SocketManager("http://localhost:8080", {
3    reconnects: true,
4    reconnectAttempts: 5,
5    compress: true
6})
7
8// Access the default namespace socket
9const defaultSocket = manager.defaultSocket
10
11// Create a socket for a specific namespace
12const roomASocket = manager.socket("/roomA")

API Reference

SocketManager

Constructor

constructor(url: string, config?: SocketManagerConfig)

  • url: The URL of the Socket.IO server.
  • config: Optional configuration object.

Properties

  • socketURL: string: The server URL.
  • status: SocketIOStatus: The manager's connection status (connected, connecting, disconnected, etc.).
  • defaultSocket: SocketIOClient: The socket for the default namespace ("/").

Methods

  • socket(namespace: string): SocketIOClient

    • Returns a SocketIOClient for the specified namespace.
  • setConfigs(config: SocketManagerConfig): void

    • Updates the manager's configuration.
  • disconnect(): void

    • Disconnects all sockets managed by this instance.
  • reconnect(): void

    • Attempts to reconnect to the server.

SocketIOClient

Properties

  • id: string | null: The unique identifier for the socket connection.
  • status: SocketIOStatus: The client's connection status (connected, connecting, etc.).

Methods

  • connect(): void

    • Initiates a connection.
  • disconnect(): void

    • Disconnects the socket.
  • emit(event: string, data: any): void

    • Sends an event to the server with associated data.
  • on(event: string, callback: (data: any[], ack: (value?: any) => void) => void): void

    • Registers an event listener.

Configuration

The SocketManagerConfig object allows you to customize connection behavior.

Key Options:

  • compress: Enables compression for WebSocket transport.
  • connectParams: A dictionary of GET parameters included in the connection URL.
  • cookies: An array of cookies to send during the initial connection.
  • forceNew: Ensures a new engine is created for every connection.
  • reconnects: Enables automatic reconnection.
  • reconnectAttempts: Sets the maximum number of reconnection attempts.
  • reconnectWait: Minimum time (in seconds) between reconnection attempts.

Example:

1const config: SocketManagerConfig = {
2    compress: true,
3    reconnects: true,
4    reconnectAttempts: 5,
5    reconnectWait: 2,
6    extraHeaders: {
7        Authorization: "Bearer token"
8    }
9}
10const manager = new SocketManager("http://example.com", config)

Common Use Cases

Emit and Listen to Events

1const socket = manager.defaultSocket
2
3socket.on("connect", () => {
4    console.log("Connected to server")
5    socket.emit("joinRoom", { room: "roomA" })
6})
7
8socket.on("message", (data) => {
9    console.log("Message received:", data)
10})

Handle Reconnection

1manager.setConfigs({ reconnects: true, reconnectAttempts: 10 })
2
3manager.defaultSocket.on("reconnect", () => {
4    console.log("Reconnected to server")
5})

Use Namespaces

1const chatSocket = manager.socket("/chat")
2
3chatSocket.on("newMessage", (data) => {
4    console.log("New message in chat:", data)
5})

Best Practices

  1. Manage Lifecycles: Always call disconnect() when sockets are no longer needed.
  2. Namespace Isolation: Use separate namespaces for logically distinct communication channels.
  3. Reconnection Strategies: Configure reconnection parameters based on your app's requirements.
  4. Error Handling: Register an on("error") handler to gracefully handle connection issues.
  5. Secure Connections: Use secure WebSocket (WSS) for sensitive data and configure secure: true.

Full Example

1// Create a SocketManager with configuration
2const manager = new SocketManager("https://example.com", {
3    reconnects: true,
4    reconnectAttempts: -1,
5    reconnectWait: 1
6})
7
8// Access the default namespace
9const socket = manager.defaultSocket
10
11// Register event handlers
12socket.on("connect", () => {
13    console.log("Connected to server")
14    socket.emit("join", { room: "lobby" })
15})
16
17socket.on("message", (data) => {
18    console.log("Message received:", data)
19})
20
21socket.on("disconnect", () => {
22    console.log("Disconnected from server")
23})
24
25// Emit a custom event
26socket.emit("sendMessage", { text: "Hello, world!" })
27
28// Disconnect when done
29setTimeout(() => {
30    manager.disconnect()
31}, 60000)