0
# WebSocket Client
1
2
Complete JSON-RPC 2.0 client implementation for both Node.js and browser environments with automatic reconnection, event subscriptions, and authentication support.
3
4
## Capabilities
5
6
### Client Constructor
7
8
Creates a WebSocket RPC client instance with automatic connection management and configurable reconnection behavior.
9
10
```typescript { .api }
11
/**
12
* WebSocket RPC client for Node.js environments
13
* Extends CommonClient with Node.js-specific WebSocket implementation
14
*/
15
class Client extends CommonClient {
16
constructor(
17
address?: string,
18
options?: IWSClientAdditionalOptions & NodeWebSocketTypeOptions,
19
generate_request_id?: (method: string, params: object | Array<any>) => number | string
20
);
21
}
22
23
/**
24
* Base client implementation with common functionality
25
* Supports both Node.js and browser environments
26
*/
27
class CommonClient extends EventEmitter {
28
constructor(
29
webSocketFactory: ICommonWebSocketFactory,
30
address?: string,
31
options?: IWSClientAdditionalOptions,
32
generate_request_id?: (method: string, params: object | Array<any>) => number | string,
33
dataPack?: DataPack<object, string>
34
);
35
}
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
import { Client } from "rpc-websockets";
42
43
// Basic client with default options
44
const client = new Client("ws://localhost:8080");
45
46
// Client with custom options
47
const client = new Client("ws://localhost:8080", {
48
autoconnect: true,
49
reconnect: true,
50
reconnect_interval: 2000,
51
max_reconnects: 10
52
});
53
54
// Client with custom request ID generation
55
const client = new Client("ws://localhost:8080", {}, (method, params) => {
56
return `${method}-${Date.now()}`;
57
});
58
```
59
60
### Connection Management
61
62
Manual connection control and status monitoring.
63
64
```typescript { .api }
65
/**
66
* Connects to a defined server if not connected already
67
*/
68
connect(): void;
69
70
/**
71
* Closes a WebSocket connection gracefully
72
* @param code - socket close code (default: 1000)
73
* @param data - optional data to be sent before closing
74
*/
75
close(code?: number, data?: string): void;
76
```
77
78
**Usage Examples:**
79
80
```typescript
81
// Manual connection
82
const client = new Client("ws://localhost:8080", { autoconnect: false });
83
client.connect();
84
85
// Connection events
86
client.on("open", () => console.log("Connected"));
87
client.on("close", (code, reason) => console.log("Disconnected", code, reason));
88
client.on("error", (error) => console.error("Connection error", error));
89
90
// Graceful disconnect
91
client.close(1000, "Client shutdown");
92
```
93
94
### RPC Method Calls
95
96
Call remote procedures with parameters, timeout support, and error handling.
97
98
```typescript { .api }
99
/**
100
* Calls a registered RPC method on server
101
* @param method - RPC method name
102
* @param params - optional method parameters (object or array)
103
* @param timeout - RPC reply timeout value in milliseconds
104
* @param ws_opts - options passed to WebSocket send method
105
* @returns Promise resolving to method result
106
*/
107
call(
108
method: string,
109
params?: IWSRequestParams,
110
timeout?: number,
111
ws_opts?: Parameters<NodeWebSocketType["send"]>[1]
112
): Promise<unknown>;
113
114
interface IWSRequestParams {
115
[x: string]: any;
116
[x: number]: any;
117
}
118
```
119
120
**Usage Examples:**
121
122
```typescript
123
// Simple method call
124
const result = await client.call("sum", [5, 3]);
125
126
// Method call with object parameters
127
const user = await client.call("getUser", { id: 123 });
128
129
// Method call with timeout
130
try {
131
const result = await client.call("slowMethod", [], 5000);
132
} catch (error) {
133
console.error("Method timed out or failed:", error.message);
134
}
135
136
// Method call with WebSocket options (Node.js only)
137
const result = await client.call("binaryMethod", data, null, { binary: true });
138
```
139
140
### Authentication
141
142
Login functionality for accessing protected methods and events.
143
144
```typescript { .api }
145
/**
146
* Logins with the other side of the connection
147
* @param params - Login credentials object
148
* @returns Promise resolving to authentication result
149
* @throws Error if authentication failed
150
*/
151
login(params: IWSRequestParams): Promise<unknown>;
152
```
153
154
**Usage Examples:**
155
156
```typescript
157
// Login with credentials
158
try {
159
await client.login({ username: "admin", password: "secret" });
160
console.log("Authentication successful");
161
162
// Now can call protected methods
163
const secretData = await client.call("getSecretData");
164
} catch (error) {
165
console.error("Authentication failed:", error.message);
166
}
167
```
168
169
### Server Method Discovery
170
171
Retrieve list of available RPC methods from the server.
172
173
```typescript { .api }
174
/**
175
* Fetches a list of client's methods registered on server
176
* @returns Promise resolving to array of method names
177
*/
178
listMethods(): Promise<unknown>;
179
```
180
181
**Usage Examples:**
182
183
```typescript
184
// Get available methods
185
const methods = await client.listMethods();
186
console.log("Available methods:", methods);
187
// Example output: ["sum", "getUser", "login", "getData"]
188
```
189
190
### Notifications
191
192
Send one-way notifications to the server without expecting a response.
193
194
```typescript { .api }
195
/**
196
* Sends a JSON-RPC 2.0 notification to server
197
* @param method - RPC method name
198
* @param params - optional method parameters
199
* @returns Promise resolving when notification is sent
200
*/
201
notify(method: string, params?: IWSRequestParams): Promise<void>;
202
```
203
204
**Usage Examples:**
205
206
```typescript
207
// Send notification without parameters
208
await client.notify("userLoggedIn");
209
210
// Send notification with parameters
211
await client.notify("userAction", {
212
action: "click",
213
element: "button",
214
timestamp: Date.now()
215
});
216
```
217
218
### Event Subscriptions
219
220
Subscribe to server events and handle real-time notifications.
221
222
```typescript { .api }
223
/**
224
* Subscribes for a defined event
225
* @param event - event name or array of event names
226
* @returns Promise resolving to subscription result
227
* @throws Error if subscription failed
228
*/
229
subscribe(event: string | Array<string>): Promise<unknown>;
230
231
/**
232
* Unsubscribes from a defined event
233
* @param event - event name or array of event names
234
* @returns Promise resolving to unsubscription result
235
* @throws Error if unsubscription failed
236
*/
237
unsubscribe(event: string | Array<string>): Promise<unknown>;
238
```
239
240
**Usage Examples:**
241
242
```typescript
243
// Subscribe to single event
244
await client.subscribe("feedUpdated");
245
client.on("feedUpdated", (data) => {
246
console.log("Feed updated:", data);
247
});
248
249
// Subscribe to multiple events
250
await client.subscribe(["userJoined", "userLeft", "messagePosted"]);
251
252
// Handle multiple events
253
client.on("userJoined", (user) => console.log("User joined:", user));
254
client.on("userLeft", (user) => console.log("User left:", user));
255
client.on("messagePosted", (message) => console.log("New message:", message));
256
257
// Unsubscribe from events
258
await client.unsubscribe("feedUpdated");
259
await client.unsubscribe(["userJoined", "userLeft"]);
260
```
261
262
### Reconnection Configuration
263
264
Configure automatic reconnection behavior for unstable network conditions.
265
266
```typescript { .api }
267
/**
268
* Enable / disable automatic reconnection
269
* @param reconnect - enable / disable reconnection
270
*/
271
setAutoReconnect(reconnect: boolean): void;
272
273
/**
274
* Set the interval between reconnection attempts
275
* @param interval - reconnection interval in milliseconds
276
*/
277
setReconnectInterval(interval: number): void;
278
279
/**
280
* Set the maximum number of reconnection attempts
281
* @param max_reconnects - maximum reconnection attempts (0 = unlimited)
282
*/
283
setMaxReconnects(max_reconnects: number): void;
284
```
285
286
**Usage Examples:**
287
288
```typescript
289
// Configure reconnection settings
290
client.setAutoReconnect(true);
291
client.setReconnectInterval(3000); // 3 seconds between attempts
292
client.setMaxReconnects(5); // Max 5 reconnection attempts
293
294
// Disable reconnection
295
client.setAutoReconnect(false);
296
297
// Unlimited reconnection attempts
298
client.setMaxReconnects(0);
299
```
300
301
## Client Configuration Types
302
303
```typescript { .api }
304
interface IWSClientAdditionalOptions {
305
/** Automatically connect on instantiation (default: true) */
306
autoconnect?: boolean;
307
/** Enable automatic reconnection (default: true) */
308
reconnect?: boolean;
309
/** Milliseconds between reconnection attempts (default: 1000) */
310
reconnect_interval?: number;
311
/** Maximum reconnection attempts, 0 = unlimited (default: 5) */
312
max_reconnects?: number;
313
}
314
315
interface ICommonWebSocket {
316
send: (
317
data: Parameters<BrowserWebSocketType["send"]>[0],
318
optionsOrCallback: ((error?: Error) => void) | Parameters<NodeWebSocketType["send"]>[1],
319
callback?: (error?: Error) => void
320
) => void;
321
close: (code?: number, reason?: string) => void;
322
addEventListener<K extends keyof WebSocketEventMap>(
323
type: K,
324
listener: (ev: WebSocketEventMap[K]) => any,
325
options?: boolean | AddEventListenerOptions
326
): void;
327
}
328
329
interface ICommonWebSocketFactory {
330
(address: string, options: IWSClientAdditionalOptions): ICommonWebSocket;
331
}
332
```
333
334
## Client Events
335
336
The client emits the following events during its lifecycle:
337
338
- **`open`**: Fired when WebSocket connection is established
339
- **`close`**: Fired when WebSocket connection is closed (code, reason)
340
- **`error`**: Fired when connection errors occur (error)
341
- **Custom events**: Any event subscribed to via `subscribe()` method