0
# Client-Side WebSocket Operations
1
2
Client-side WebSocket implementation providing outbound connection capabilities with both native API and W3C-compliant interfaces for connecting to WebSocket servers.
3
4
## Capabilities
5
6
### WebSocketClient
7
8
Native WebSocket client for creating outbound connections with full configuration control.
9
10
```javascript { .api }
11
/**
12
* WebSocket client for creating outbound connections
13
* @param config - Client configuration options
14
*/
15
class WebSocketClient extends EventEmitter {
16
constructor(config?: ClientConfig);
17
18
/**
19
* Connect to WebSocket server
20
* @param requestUrl - WebSocket URL (ws:// or wss://)
21
* @param protocols - Array of protocols or single protocol string
22
* @param origin - Origin header value
23
* @param headers - Additional HTTP headers object
24
* @param extraRequestOptions - Additional options for HTTP request
25
*/
26
connect(requestUrl: string, protocols?: string | string[], origin?: string, headers?: object, extraRequestOptions?: object): void;
27
28
/** Abort connection attempt */
29
abort(): void;
30
31
/** Client configuration object */
32
readonly config: ClientConfig;
33
34
/** Parsed URL object of connection target */
35
readonly url: URL;
36
37
/** Array of requested protocols */
38
readonly protocols: string[];
39
40
/** Origin header value */
41
readonly origin: string;
42
43
/** Negotiated protocol (after successful connection) */
44
readonly protocol: string;
45
46
/** Whether connection uses TLS/SSL (wss://) */
47
readonly secure: boolean;
48
}
49
```
50
51
**Configuration:**
52
53
```javascript { .api }
54
interface ClientConfig {
55
/** Maximum frame size in bytes (default: 1MiB) */
56
maxReceivedFrameSize?: number;
57
58
/** Maximum message size in bytes (default: 8MiB) */
59
maxReceivedMessageSize?: number;
60
61
/** Whether to fragment outgoing messages (default: true) */
62
fragmentOutgoingMessages?: boolean;
63
64
/** Fragment messages larger than this size (default: 16KiB) */
65
fragmentationThreshold?: number;
66
67
/** WebSocket protocol version 8 or 13 (default: 13) */
68
webSocketVersion?: number;
69
70
/** Assemble fragmented messages (default: true) */
71
assembleFragments?: boolean;
72
73
/** Disable Nagle algorithm (default: true) */
74
disableNagleAlgorithm?: boolean;
75
76
/** Close frame timeout in milliseconds (default: 5000) */
77
closeTimeout?: number;
78
79
/** TLS connection options object */
80
tlsOptions?: object;
81
}
82
```
83
84
**Events:**
85
86
- `'connect'` - `(WebSocketConnection)` - Connection successful
87
- `'connectFailed'` - `(error)` - Connection failed
88
- `'httpResponse'` - `(response, client)` - Non-101 HTTP response received
89
90
**Usage Example:**
91
92
```javascript
93
const WebSocket = require('websocket');
94
95
const client = new WebSocket.client({
96
maxReceivedFrameSize: 1024 * 1024,
97
maxReceivedMessageSize: 8 * 1024 * 1024,
98
webSocketVersion: 13,
99
tlsOptions: {
100
rejectUnauthorized: false // For self-signed certificates
101
}
102
});
103
104
client.on('connectFailed', function(error) {
105
console.log('Connect Error: ' + error.toString());
106
});
107
108
client.on('connect', function(connection) {
109
console.log('WebSocket Client Connected');
110
console.log('Connected Protocol: ' + connection.protocol);
111
112
connection.on('error', function(error) {
113
console.log("Connection Error: " + error.toString());
114
});
115
116
connection.on('close', function() {
117
console.log('Connection Closed');
118
});
119
120
connection.on('message', function(message) {
121
if (message.type === 'utf8') {
122
console.log("Received: '" + message.utf8Data + "'");
123
}
124
});
125
126
// Send a message
127
if (connection.connected) {
128
connection.sendUTF('Hello Server!');
129
}
130
});
131
132
// Connect to server
133
client.connect('ws://localhost:8080/', ['echo-protocol'], 'http://localhost', {
134
'User-Agent': 'My WebSocket Client'
135
});
136
```
137
138
### W3CWebSocket
139
140
W3C-compliant WebSocket API implementation providing standard browser-like interface.
141
142
```javascript { .api }
143
/**
144
* W3C-compliant WebSocket API implementation
145
* @param url - WebSocket URL (ws:// or wss://)
146
* @param protocols - Array of protocols or single protocol string
147
* @param origin - Origin header value
148
* @param headers - Additional HTTP headers object
149
* @param requestOptions - Additional request options
150
* @param clientConfig - WebSocketClient configuration
151
*/
152
class W3CWebSocket {
153
constructor(url: string, protocols?: string | string[], origin?: string, headers?: object, requestOptions?: object, clientConfig?: ClientConfig);
154
155
/**
156
* Send text or binary data
157
* @param data - String, Buffer, or ArrayBuffer to send
158
*/
159
send(data: string | Buffer | ArrayBuffer): void;
160
161
/**
162
* Close connection
163
* @param code - Close status code (default: 1000)
164
* @param reason - Close reason string
165
*/
166
close(code?: number, reason?: string): void;
167
168
/**
169
* Add event listener
170
* @param type - Event type ('open', 'message', 'error', 'close')
171
* @param listener - Event handler function
172
*/
173
addEventListener(type: string, listener: (event: Event) => void): void;
174
175
/**
176
* Remove event listener
177
* @param type - Event type
178
* @param listener - Event handler function to remove
179
*/
180
removeEventListener(type: string, listener: (event: Event) => void): void;
181
182
/** WebSocket URL */
183
readonly url: string;
184
185
/** Connection state (0-3) */
186
readonly readyState: number;
187
188
/** Negotiated protocol */
189
readonly protocol: string;
190
191
/** Negotiated extensions (always empty string) */
192
readonly extensions: string;
193
194
/** Queued data amount in bytes (always 0) */
195
readonly bufferedAmount: number;
196
197
/** Binary data type ('arraybuffer') */
198
binaryType: string;
199
200
/** Open event handler */
201
onopen: ((event: Event) => void) | null;
202
203
/** Message event handler */
204
onmessage: ((event: MessageEvent) => void) | null;
205
206
/** Error event handler */
207
onerror: ((event: Event) => void) | null;
208
209
/** Close event handler */
210
onclose: ((event: CloseEvent) => void) | null;
211
}
212
```
213
214
**ReadyState Constants:**
215
216
```javascript { .api }
217
const ReadyState = {
218
CONNECTING: 0,
219
OPEN: 1,
220
CLOSING: 2,
221
CLOSED: 3
222
};
223
224
// Access via W3CWebSocket static properties
225
W3CWebSocket.CONNECTING = 0;
226
W3CWebSocket.OPEN = 1;
227
W3CWebSocket.CLOSING = 2;
228
W3CWebSocket.CLOSED = 3;
229
```
230
231
**Events (via addEventListener):**
232
233
- `'open'` - Connection opened
234
- `'message'` - Message received (event.data contains the data)
235
- `'error'` - Connection error
236
- `'close'` - Connection closed (event.code, event.reason, event.wasClean)
237
238
**Usage Example:**
239
240
```javascript
241
const { w3cwebsocket: W3CWebSocket } = require('websocket');
242
243
const client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');
244
245
client.onerror = function() {
246
console.log('Connection Error');
247
};
248
249
client.onopen = function() {
250
console.log('WebSocket Client Connected');
251
252
function sendNumber() {
253
if (client.readyState === client.OPEN) {
254
var number = Math.round(Math.random() * 0xFFFFFF);
255
client.send(number.toString());
256
setTimeout(sendNumber, 1000);
257
}
258
}
259
sendNumber();
260
};
261
262
client.onclose = function() {
263
console.log('Connection Closed');
264
};
265
266
client.onmessage = function(e) {
267
if (typeof e.data === 'string') {
268
console.log("Received: '" + e.data + "'");
269
}
270
};
271
272
// Using addEventListener instead of direct assignment
273
client.addEventListener('open', function() {
274
console.log('Connection established via addEventListener');
275
});
276
277
client.addEventListener('message', function(e) {
278
console.log('Message via addEventListener: ' + e.data);
279
});
280
```
281
282
**Browser Compatibility:**
283
284
For browser usage, import the browser-specific build:
285
286
```javascript
287
// Browser environment
288
const { w3cwebsocket: W3CWebSocket } = require('websocket/lib/browser');
289
290
// If native WebSocket is available, W3CWebSocket will be null
291
// and you should use the native WebSocket instead
292
const WebSocketClass = W3CWebSocket || WebSocket;
293
const client = new WebSocketClass('ws://localhost:8080/');
294
```
295
296
### Advanced Client Features
297
298
**Custom Headers and Authentication:**
299
300
```javascript
301
const client = new WebSocket.client();
302
303
client.connect('wss://secure.example.com/websocket', ['custom-protocol'], 'https://example.com', {
304
'Authorization': 'Bearer ' + token,
305
'X-Custom-Header': 'custom-value'
306
}, {
307
// Extra request options
308
timeout: 10000,
309
agent: customHttpAgent
310
});
311
```
312
313
**TLS Configuration:**
314
315
```javascript
316
const client = new WebSocket.client({
317
tlsOptions: {
318
key: fs.readFileSync('client-key.pem'),
319
cert: fs.readFileSync('client-cert.pem'),
320
ca: fs.readFileSync('ca-cert.pem'),
321
rejectUnauthorized: true
322
}
323
});
324
```
325
326
**Protocol Version Selection:**
327
328
```javascript
329
// Force WebSocket protocol version 8
330
const client = new WebSocket.client({
331
webSocketVersion: 8
332
});
333
334
// Default is version 13 (latest)
335
const modernClient = new WebSocket.client({
336
webSocketVersion: 13
337
});
338
```
339
340
## Types
341
342
### Event Types
343
344
```javascript { .api }
345
interface MessageEvent {
346
data: string | ArrayBuffer;
347
origin: string;
348
lastEventId: string;
349
source: any;
350
ports: MessagePort[];
351
}
352
353
interface CloseEvent {
354
code: number;
355
reason: string;
356
wasClean: boolean;
357
}
358
359
interface Event {
360
type: string;
361
target: any;
362
currentTarget: any;
363
eventPhase: number;
364
bubbles: boolean;
365
cancelable: boolean;
366
timeStamp: number;
367
defaultPrevented: boolean;
368
}
369
```