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:
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
SocketIOClientfor the specified namespace.
- Returns a
-
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:
Common Use Cases
Emit and Listen to Events
Handle Reconnection
Use Namespaces
Best Practices
- Manage Lifecycles: Always call
disconnect()when sockets are no longer needed. - Namespace Isolation: Use separate namespaces for logically distinct communication channels.
- Reconnection Strategies: Configure reconnection parameters based on your app's requirements.
- Error Handling: Register an
on("error")handler to gracefully handle connection issues. - Secure Connections: Use secure WebSocket (WSS) for sensitive data and configure
secure: true.
