A wrapper for socket.io-client
that handles best practices and edge cases in a more abstracted and opinionated manner.
ClientSocketManager
is a flexible and robust manager for handling socket connections using socket.io-client
. It provides easy setup and management of socket connections with support for automatic reconnections, event handling, and visibility change management.
First, install the necessary dependencies:
npm install @tapsioss/client-socket-manager socket.io-client
Here is an example of how to use ClientSocketManager
in your project:
import { ClientSocketManager } from '@tapsioss/client-socket-manager';
const socketManager = new ClientSocketManager('http://localhost:3000', {
eventHandlers: {
onSocketConnection() {
console.log('Socket connected');
},
onSocketDisconnection(reason) {
console.log('Socket disconnected:', reason);
},
onSuccessfulReconnection(attempt) {
console.log('Socket reconnected after', attempt, 'attempt(s)');
},
onAnySubscribedMessageReceived(channel, message) {
console.log(`Message received on ${channel}:`, message);
},
},
});
// Emit an event
socketManager.emit('message', 'Hello, world!');
// Subscribe to a channel
socketManager.subscribe('message', (msg) => {
console.log('Message from server:', msg);
});
constructor(uri: string, options?: Partial<ClientSocketManagerOptions>)
-
uri
: The URI of the socket server. -
options
: (optional): Configuration options for the socket connection.
We have extended socket-io's options to include additional options:
-
eventHandlers
: Handlers for various socket events.-
onInit
: Fired upon instantiation. -
onDispose
: Fired upon disposal. -
onSocketConnection
: Fired when the socket is successfully connected. -
onSocketDisconnection
: Fired when the socket is disconnected. -
onServerPing
: Fired when a ping packet is received from the server. -
onConnectionError
: Fired upon a connection error. -
onReconnecting
: Fired upon an attempt to reconnect. -
onReconnectingError
: Fired upon a reconnection attempt error. -
onReconnectionFailure
: Fired when couldn't reconnect withinreconnectionAttempts
. -
onSuccessfulReconnection
: Fired upon a successful reconnection. -
onAnySubscribedMessageReceived
: Fired when any message is received from a subscribed channel. -
onVisiblePage
: Fired when the page'svisibilityState
changes tovisible
. -
onHiddenPage
: Fired when the page'svisibilityState
changes tohidden
.
-
A unique identifier for the session. null
when the socket is not connected.
Whether the socket is currently connected to the server.
Whether the client is disposed.
Whether the connection state was recovered after a temporary disconnection.
Whether the Socket will try to reconnect when its Manager connects or reconnects.
emit<Ev extends EventNames<EmitEvents>>(
channel: Ev,
...args: EventParams<EmitEvents, Ev>
): void;
Emits an event to the socket identified by the channel name.
-
channel
: The name of the channel to emit the event to. -
args
: The arguments to pass with the event.
subscribe<Ev extends EventNames<ListenEvents>>(
channel: Ev,
cb: ListenEvents[Ev],
options?: {
onSubscriptionComplete?: (channel: string) => void;
signal?: AbortSignal;
},
): void;
Subscribes to a specified channel with a callback function. Ensures that only one listener exists per channel.
-
channel
: The name of the channel to subscribe to. -
cb
: The callback function to invoke when a message is received on the channel. -
options
: Optional parameters.-
onSubscriptionComplete
: The callback function to invoke when the subscription is complete. -
signal
: TheAbortSignal
to unsubscribe the listener upon abortion.
-
unsubscribe<Ev extends EventNames<ListenEvents>>(
channel: Ev,
cb?: ListenEvents[Ev],
): void;
Removes the listener for the specified channel. If no callback is provided, it removes all listeners for that channel.
-
channel
: The name of the channel whose listener should be deleted. -
cb
(optional): The subscriber callback function to remove.
connect(): void;
Manually connects/reconnects the socket.
disconnect(): void;
Manually disconnects the socket. In that case, the socket will not try to reconnect. If this is the last active Socket instance of the Manager, the low-level connection will be closed.
dispose(): void;
Disposes of the socket, manager, and engine, ensuring all connections are closed and cleaned up.
The package also exports a stubbed version of the socket manager for use in testing or server-side rendering (SSR) environments:
import { ClientSocketManagerStub } from '@tapsioss/client-socket-manager';
const stub = new ClientSocketManagerStub("mock://url", {
eventHandlers: {
onSocketConnection() {
console.log("Simulated connection");
},
},
});
stub.connect(); // Triggers onSocketConnection
stub.emit("message", "noop"); // No-op
stub.dispose(); // Marks the client as disposed
- Prevents actual network communication in unit tests and SSR.
- Mimics the API surface of the real
ClientSocketManager
. - Triggers configured event handlers like
onSocketConnection
andonSocketDisconnection
.
- Methods like
emit
,subscribe
, andunsubscribe
are no-ops. -
connect()
anddisconnect()
simulate connection lifecycle events. - The
connected
,disposed
,id
, and other properties behave consistently with a mock socket.
This project is licensed under the terms of the MIT license.