0
# RPC WebSockets
1
2
RPC WebSockets is a comprehensive JSON-RPC 2.0 implementation over WebSockets for Node.js and browser environments. It enables bidirectional real-time communication between clients and servers with support for RPC method calls, event subscriptions, and notifications.
3
4
## Package Information
5
6
- **Package Name**: rpc-websockets
7
- **Package Type**: npm
8
- **Language**: TypeScript/JavaScript
9
- **Installation**: `npm install rpc-websockets`
10
11
## Core Imports
12
13
For Node.js environments:
14
15
```typescript
16
import { Client, Server, createError } from "rpc-websockets";
17
```
18
19
For browser environments (Server and createError not available):
20
21
```typescript
22
import { Client } from "rpc-websockets";
23
```
24
25
CommonJS (Node.js):
26
27
```javascript
28
const { Client, Server, createError } = require("rpc-websockets");
29
```
30
31
## Basic Usage
32
33
### Client Usage
34
35
```typescript
36
import { Client } from "rpc-websockets";
37
38
// Create and connect to WebSocket RPC server
39
const client = new Client("ws://localhost:8080");
40
41
// Wait for connection
42
client.on("open", async () => {
43
// Call RPC method
44
const result = await client.call("sum", [5, 3]);
45
console.log(result); // 8
46
47
// Subscribe to events
48
await client.subscribe("feedUpdated");
49
client.on("feedUpdated", (data) => {
50
console.log("Feed updated:", data);
51
});
52
53
// Send notification
54
await client.notify("userAction", { action: "click", element: "button" });
55
});
56
```
57
58
### Server Usage
59
60
```typescript
61
import { Server } from "rpc-websockets";
62
63
// Create WebSocket RPC server
64
const server = new Server({ port: 8080 });
65
66
// Register RPC methods
67
server.register("sum", (params) => {
68
return params[0] + params[1];
69
});
70
71
// Create and emit events
72
server.event("feedUpdated");
73
server.emit("feedUpdated", { timestamp: Date.now() });
74
75
// Register protected method requiring authentication
76
server.register("getSecretData", () => {
77
return { secret: "confidential data" };
78
}).protected();
79
```
80
81
## Architecture
82
83
RPC WebSockets is built around several key components:
84
85
- **Environment-Specific Builds**:
86
- Node.js build includes Client, Server, createError, and all utilities
87
- Browser build includes only Client and core utilities (no Server functionality)
88
- Separate WebSocket implementations optimized for each environment
89
- **Client Implementation**: Unified Client class with CommonClient base for cross-platform compatibility
90
- **Server Implementation**: Full-featured WebSocket server with namespace support (Node.js only)
91
- **JSON-RPC 2.0 Protocol**: Complete implementation of the JSON-RPC 2.0 specification
92
- **Event System**: Bidirectional event subscription and emission capabilities
93
- **Authentication System**: Method and event protection with login middleware
94
- **Reconnection Logic**: Automatic reconnection with configurable intervals and limits
95
- **Data Serialization**: Pluggable data encoding/decoding system with JSON default
96
97
## Capabilities
98
99
### WebSocket Client
100
101
Full-featured JSON-RPC 2.0 client for both Node.js and browser environments with automatic reconnection, event subscriptions, and authentication support.
102
103
```typescript { .api }
104
class Client extends CommonClient {
105
constructor(
106
address?: string,
107
options?: IWSClientAdditionalOptions & NodeWebSocketTypeOptions,
108
generate_request_id?: (method: string, params: object | Array<any>) => number | string
109
);
110
}
111
112
interface IWSClientAdditionalOptions {
113
autoconnect?: boolean;
114
reconnect?: boolean;
115
reconnect_interval?: number;
116
max_reconnects?: number;
117
}
118
```
119
120
[WebSocket Client](./client.md)
121
122
### WebSocket Server
123
124
JSON-RPC 2.0 server implementation with method registration, event management, namespace support, and authentication middleware.
125
126
```typescript { .api }
127
class Server extends EventEmitter {
128
wss: InstanceType<typeof WebSocketServer>;
129
130
constructor(
131
options: NodeWebSocket.ServerOptions,
132
dataPack?: DataPack<object, string>
133
);
134
135
register(
136
name: string,
137
fn: (params: IRPCMethodParams, socket_id: string) => void,
138
ns?: string
139
): IMethod;
140
141
event(name: string, ns?: string): IEvent;
142
}
143
```
144
145
[WebSocket Server](./server.md)
146
147
### Data Serialization
148
149
Pluggable data encoding and decoding system for custom serialization formats beyond the default JSON implementation.
150
151
```typescript { .api }
152
interface DataPack<T, R extends string | ArrayBufferLike | Blob | ArrayBufferView> {
153
encode(value: T): R;
154
decode(value: R): T;
155
}
156
157
class DefaultDataPack implements DataPack<Object, string> {
158
encode(value: Object): string;
159
decode(value: string): Object;
160
}
161
```
162
163
### Utility Functions
164
165
Standalone utility functions for error handling and JSON-RPC compliance. **Note**: Available in Node.js environments only.
166
167
```typescript { .api }
168
/**
169
* Creates a JSON-RPC 2.0-compliant error
170
* @param code - JSON-RPC error code (e.g., -32700 for parse error, -32600 for invalid request)
171
* @param details - optional additional error details
172
* @returns JSON-RPC error object with code, message, and optional data
173
*/
174
function createError(code: number, details?: string): IRPCError;
175
```
176
177
**Usage Example:**
178
179
```typescript
180
import { createError } from "rpc-websockets";
181
182
// Create a custom error
183
const error = createError(-32001, "Custom application error");
184
// Result: { code: -32001, message: "Server error", data: "Custom application error" }
185
186
// Create a standard JSON-RPC error
187
const parseError = createError(-32700);
188
// Result: { code: -32700, message: "Parse error" }
189
```
190
191
### Advanced APIs
192
193
WebSocket factory functions for advanced use cases and custom implementations.
194
195
```typescript { .api }
196
/**
197
* Node.js WebSocket factory function
198
* Creates WebSocket instances optimized for Node.js environments
199
*/
200
function WebSocket(address: string, options: IWSClientAdditionalOptions): ICommonWebSocket;
201
```
202
203
**Usage Example:**
204
205
```typescript
206
import { WebSocket, CommonClient } from "rpc-websockets";
207
208
// Create a custom client with the Node.js WebSocket factory
209
const customClient = new CommonClient(
210
WebSocket,
211
"ws://localhost:8080",
212
{ reconnect: false }
213
);
214
```
215
216
**Note**: The browser build exports a different WebSocket factory optimized for browser environments. Most users should use the `Client` class directly instead of these factory functions.
217
218
## Common Types
219
220
```typescript { .api }
221
interface IRPCMethodParams {
222
[x: string]: any;
223
}
224
225
interface IWSRequestParams {
226
[x: string]: any;
227
[x: number]: any;
228
}
229
230
interface IQueue {
231
[x: number | string]: IQueueElement;
232
}
233
234
interface IQueueElement {
235
promise: [
236
Parameters<ConstructorParameters<typeof Promise>[0]>[0],
237
Parameters<ConstructorParameters<typeof Promise>[0]>[1]
238
];
239
timeout?: ReturnType<typeof setTimeout>;
240
}
241
242
interface IMethod {
243
public(): void;
244
protected(): void;
245
}
246
247
interface IEvent {
248
public(): void;
249
protected(): void;
250
}
251
252
interface IRPCError {
253
code: number;
254
message: string;
255
data?: string;
256
}
257
258
interface ICommonWebSocket {
259
send: (
260
data: Parameters<BrowserWebSocketType["send"]>[0],
261
optionsOrCallback: ((error?: Error) => void) | Parameters<NodeWebSocketType["send"]>[1],
262
callback?: (error?: Error) => void
263
) => void;
264
close: (code?: number, reason?: string) => void;
265
addEventListener<K extends keyof WebSocketEventMap>(
266
type: K,
267
listener: (ev: WebSocketEventMap[K]) => any,
268
options?: boolean | AddEventListenerOptions
269
): void;
270
}
271
272
interface ICommonWebSocketFactory {
273
(address: string, options: IWSClientAdditionalOptions): ICommonWebSocket;
274
}
275
276
type NodeWebSocketTypeOptions = NodeWebSocket.ClientOptions;
277
278
type BrowserWebSocketType = InstanceType<typeof WebSocket>;
279
type NodeWebSocketType = InstanceType<typeof NodeWebSocket>;
280
```