JSON-RPC 2.0 implementation over WebSockets for Node.js and browser with bidirectional communication support
—
Complete JSON-RPC 2.0 client implementation for both Node.js and browser environments with automatic reconnection, event subscriptions, and authentication support.
Creates a WebSocket RPC client instance with automatic connection management and configurable reconnection behavior.
/**
* WebSocket RPC client for Node.js environments
* Extends CommonClient with Node.js-specific WebSocket implementation
*/
class Client extends CommonClient {
constructor(
address?: string,
options?: IWSClientAdditionalOptions & NodeWebSocketTypeOptions,
generate_request_id?: (method: string, params: object | Array<any>) => number | string
);
}
/**
* Base client implementation with common functionality
* Supports both Node.js and browser environments
*/
class CommonClient extends EventEmitter {
constructor(
webSocketFactory: ICommonWebSocketFactory,
address?: string,
options?: IWSClientAdditionalOptions,
generate_request_id?: (method: string, params: object | Array<any>) => number | string,
dataPack?: DataPack<object, string>
);
}Usage Examples:
import { Client } from "rpc-websockets";
// Basic client with default options
const client = new Client("ws://localhost:8080");
// Client with custom options
const client = new Client("ws://localhost:8080", {
autoconnect: true,
reconnect: true,
reconnect_interval: 2000,
max_reconnects: 10
});
// Client with custom request ID generation
const client = new Client("ws://localhost:8080", {}, (method, params) => {
return `${method}-${Date.now()}`;
});Manual connection control and status monitoring.
/**
* Connects to a defined server if not connected already
*/
connect(): void;
/**
* Closes a WebSocket connection gracefully
* @param code - socket close code (default: 1000)
* @param data - optional data to be sent before closing
*/
close(code?: number, data?: string): void;Usage Examples:
// Manual connection
const client = new Client("ws://localhost:8080", { autoconnect: false });
client.connect();
// Connection events
client.on("open", () => console.log("Connected"));
client.on("close", (code, reason) => console.log("Disconnected", code, reason));
client.on("error", (error) => console.error("Connection error", error));
// Graceful disconnect
client.close(1000, "Client shutdown");Call remote procedures with parameters, timeout support, and error handling.
/**
* Calls a registered RPC method on server
* @param method - RPC method name
* @param params - optional method parameters (object or array)
* @param timeout - RPC reply timeout value in milliseconds
* @param ws_opts - options passed to WebSocket send method
* @returns Promise resolving to method result
*/
call(
method: string,
params?: IWSRequestParams,
timeout?: number,
ws_opts?: Parameters<NodeWebSocketType["send"]>[1]
): Promise<unknown>;
interface IWSRequestParams {
[x: string]: any;
[x: number]: any;
}Usage Examples:
// Simple method call
const result = await client.call("sum", [5, 3]);
// Method call with object parameters
const user = await client.call("getUser", { id: 123 });
// Method call with timeout
try {
const result = await client.call("slowMethod", [], 5000);
} catch (error) {
console.error("Method timed out or failed:", error.message);
}
// Method call with WebSocket options (Node.js only)
const result = await client.call("binaryMethod", data, null, { binary: true });Login functionality for accessing protected methods and events.
/**
* Logins with the other side of the connection
* @param params - Login credentials object
* @returns Promise resolving to authentication result
* @throws Error if authentication failed
*/
login(params: IWSRequestParams): Promise<unknown>;Usage Examples:
// Login with credentials
try {
await client.login({ username: "admin", password: "secret" });
console.log("Authentication successful");
// Now can call protected methods
const secretData = await client.call("getSecretData");
} catch (error) {
console.error("Authentication failed:", error.message);
}Retrieve list of available RPC methods from the server.
/**
* Fetches a list of client's methods registered on server
* @returns Promise resolving to array of method names
*/
listMethods(): Promise<unknown>;Usage Examples:
// Get available methods
const methods = await client.listMethods();
console.log("Available methods:", methods);
// Example output: ["sum", "getUser", "login", "getData"]Send one-way notifications to the server without expecting a response.
/**
* Sends a JSON-RPC 2.0 notification to server
* @param method - RPC method name
* @param params - optional method parameters
* @returns Promise resolving when notification is sent
*/
notify(method: string, params?: IWSRequestParams): Promise<void>;Usage Examples:
// Send notification without parameters
await client.notify("userLoggedIn");
// Send notification with parameters
await client.notify("userAction", {
action: "click",
element: "button",
timestamp: Date.now()
});Subscribe to server events and handle real-time notifications.
/**
* Subscribes for a defined event
* @param event - event name or array of event names
* @returns Promise resolving to subscription result
* @throws Error if subscription failed
*/
subscribe(event: string | Array<string>): Promise<unknown>;
/**
* Unsubscribes from a defined event
* @param event - event name or array of event names
* @returns Promise resolving to unsubscription result
* @throws Error if unsubscription failed
*/
unsubscribe(event: string | Array<string>): Promise<unknown>;Usage Examples:
// Subscribe to single event
await client.subscribe("feedUpdated");
client.on("feedUpdated", (data) => {
console.log("Feed updated:", data);
});
// Subscribe to multiple events
await client.subscribe(["userJoined", "userLeft", "messagePosted"]);
// Handle multiple events
client.on("userJoined", (user) => console.log("User joined:", user));
client.on("userLeft", (user) => console.log("User left:", user));
client.on("messagePosted", (message) => console.log("New message:", message));
// Unsubscribe from events
await client.unsubscribe("feedUpdated");
await client.unsubscribe(["userJoined", "userLeft"]);Configure automatic reconnection behavior for unstable network conditions.
/**
* Enable / disable automatic reconnection
* @param reconnect - enable / disable reconnection
*/
setAutoReconnect(reconnect: boolean): void;
/**
* Set the interval between reconnection attempts
* @param interval - reconnection interval in milliseconds
*/
setReconnectInterval(interval: number): void;
/**
* Set the maximum number of reconnection attempts
* @param max_reconnects - maximum reconnection attempts (0 = unlimited)
*/
setMaxReconnects(max_reconnects: number): void;Usage Examples:
// Configure reconnection settings
client.setAutoReconnect(true);
client.setReconnectInterval(3000); // 3 seconds between attempts
client.setMaxReconnects(5); // Max 5 reconnection attempts
// Disable reconnection
client.setAutoReconnect(false);
// Unlimited reconnection attempts
client.setMaxReconnects(0);interface IWSClientAdditionalOptions {
/** Automatically connect on instantiation (default: true) */
autoconnect?: boolean;
/** Enable automatic reconnection (default: true) */
reconnect?: boolean;
/** Milliseconds between reconnection attempts (default: 1000) */
reconnect_interval?: number;
/** Maximum reconnection attempts, 0 = unlimited (default: 5) */
max_reconnects?: number;
}
interface ICommonWebSocket {
send: (
data: Parameters<BrowserWebSocketType["send"]>[0],
optionsOrCallback: ((error?: Error) => void) | Parameters<NodeWebSocketType["send"]>[1],
callback?: (error?: Error) => void
) => void;
close: (code?: number, reason?: string) => void;
addEventListener<K extends keyof WebSocketEventMap>(
type: K,
listener: (ev: WebSocketEventMap[K]) => any,
options?: boolean | AddEventListenerOptions
): void;
}
interface ICommonWebSocketFactory {
(address: string, options: IWSClientAdditionalOptions): ICommonWebSocket;
}The client emits the following events during its lifecycle:
open: Fired when WebSocket connection is establishedclose: Fired when WebSocket connection is closed (code, reason)error: Fired when connection errors occur (error)subscribe() method