WebSocketManager
Managed WebSocket connection with automatic reconnection and exponential backoff.
Defined in: src/utils/websocket.ts:206
Managed WebSocket connection with automatic reconnection and exponential backoff.
Remarks
This class wraps the browser’s native WebSocket API and adds:
- Connection timeout: Rejects the connection promise if the socket doesn’t open within the configured timeout period.
- Automatic reconnection: When enabled, automatically attempts to reconnect after unexpected disconnections using exponential backoff.
- State management: Tracks the connection state through a well-defined state machine (WebSocketState).
- Event dispatching: Routes WebSocket events to registered handlers.
- Clean shutdown: Provides a graceful
disconnect()method that waits for the close handshake to complete.
Reconnection uses exponential backoff with the formula: delay = min(initialDelay * backoffMultiplier^(attempt-1), maxDelay)
Example
const ws = new WebSocketManager({
url: 'wss://api.deepgram.com/v1/speak',
connectionTimeout: 10000,
reconnection: { enabled: false },
});
ws.setHandlers({
onMessage: (event) => processAudio(event.data),
onError: (error) => console.error(error),
});
await ws.connect();
ws.send(JSON.stringify({ text: 'Hello' }));
await ws.disconnect();
See
- WebSocketState - Connection state enumeration.
- WebSocketManagerOptions - Configuration options.
- WebSocketHandlers - Event handler interface.
Constructors
Constructor
new WebSocketManager(options): WebSocketManager;
Defined in: src/utils/websocket.ts:234
Creates a new WebSocketManager instance.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | WebSocketManagerOptions | Configuration options for the WebSocket connection. Default reconnection settings are applied if not provided. |
Returns
WebSocketManager
Example
const ws = new WebSocketManager({
url: 'wss://api.example.com/stream',
connectionTimeout: 5000,
reconnection: { enabled: true, maxAttempts: 3 },
});
Methods
connect()
connect(): Promise<void>;
Defined in: src/utils/websocket.ts:311
Opens a WebSocket connection to the configured URL.
Returns
Promise<void>
A promise that resolves when the WebSocket is open.
Remarks
Returns a promise that resolves when the connection is successfully opened, or rejects if the connection times out or fails. If already connected or a connection attempt is in progress, the call is a no-op.
After a successful connection, the reconnect attempt counter is reset and the onOpen handler is called.
Throws
TimeoutError if the connection does not open within the configured timeout.
Throws
WebSocketError if the WebSocket constructor or connection fails.
disconnect()
disconnect(code?, reason?): Promise<void>;
Defined in: src/utils/websocket.ts:475
Gracefully closes the WebSocket connection.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
code | number | 1000 | The WebSocket close code. |
reason | string | 'Normal closure' | A human-readable reason for closing. |
Returns
Promise<void>
A promise that resolves when the connection has been closed.
Remarks
Disables automatic reconnection, cancels any pending reconnection timer, and initiates a clean WebSocket close handshake. Waits up to 5 seconds for the close handshake to complete before force-cleaning resources.
If the WebSocket is already closed or disconnected, this is a no-op.
Default Value
code: 1000
Default Value
reason: 'Normal closure'
getState()
getState(): WebSocketState;
Defined in: src/utils/websocket.ts:256
Returns the current connection state.
Returns
The current WebSocketState.
isConnected()
isConnected(): boolean;
Defined in: src/utils/websocket.ts:269
Checks whether the WebSocket is currently connected and ready.
Returns
boolean
true if connected and ready, false otherwise.
Remarks
Returns true only when both the internal state is CONNECTED and the underlying WebSocket.readyState is OPEN.
send()
send(data): void;
Defined in: src/utils/websocket.ts:450
Sends data through the open WebSocket connection.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | string | ArrayBuffer | Blob | The data to send. Accepts strings (for JSON messages), ArrayBuffer (for binary audio data), or Blob. |
Returns
void
Throws
WebSocketError if the WebSocket is not connected.
Example
// Send JSON message
ws.send(JSON.stringify({ text: 'Hello, world!' }));
// Send binary audio data
ws.send(audioArrayBuffer);
setHandlers()
setHandlers(handlers): void;
Defined in: src/utils/websocket.ts:291
Registers event handlers for WebSocket lifecycle events.
Parameters
| Parameter | Type | Description |
|---|---|---|
handlers | WebSocketHandlers | The event handler callbacks to register. |
Returns
void
Remarks
Merges the provided handlers with any previously registered handlers. Calling this method multiple times will overwrite handlers for the same event type.
Example
ws.setHandlers({
onMessage: (event) => handleMessage(event),
onError: (error) => handleError(error),
});