Skip to content

Commit 3a3fb52

Browse files
theturtle32claude
andcommitted
Update README.md with v2.0 Promise-based API examples
- Add async/await examples as primary documentation - Show both event handler and async iterator patterns - Move callback-based examples to collapsible sections - Update feature list to highlight Promise support - Demonstrate modern JavaScript patterns (const, async functions) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 504bfc9 commit 3a3fb52

File tree

1 file changed

+182
-8
lines changed

1 file changed

+182
-8
lines changed

README.md

Lines changed: 182 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,12 @@ Current Features:
8080
- TLS supported for outbound connections via WebSocketClient
8181
- TLS supported for server connections (use https.createServer instead of http.createServer)
8282
- Thanks to [pors](https://github.com/pors) for confirming this!
83+
- **Promise-based API (v2.0+)** - All async operations support both callbacks and Promises
84+
- `client.connect()` returns a Promise
85+
- `connection.send()`, `sendUTF()`, `sendBytes()` return Promises when no callback provided
86+
- `connection.close()` returns a Promise
87+
- `connection.messages()` async iterator for consuming messages
88+
- Fully backward compatible - existing callback-based code works unchanged
8389
- Cookie setting and parsing
8490
- Tunable settings
8591
- Max Receivable Frame Size
@@ -106,12 +112,14 @@ Server Example
106112

107113
Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
108114

115+
### Using Async/Await with Event Handlers (v2.0+)
116+
109117
```javascript
110118
#!/usr/bin/env node
111-
var WebSocketServer = require('websocket').server;
112-
var http = require('http');
119+
const WebSocketServer = require('websocket').server;
120+
const http = require('http');
113121

114-
var server = http.createServer(function(request, response) {
122+
const server = http.createServer(function(request, response) {
115123
console.log((new Date()) + ' Received request for ' + request.url);
116124
response.writeHead(404);
117125
response.end();
@@ -120,7 +128,7 @@ server.listen(8080, function() {
120128
console.log((new Date()) + ' Server is listening on port 8080');
121129
});
122130

123-
wsServer = new WebSocketServer({
131+
const wsServer = new WebSocketServer({
124132
httpServer: server,
125133
// You should not use autoAcceptConnections for production
126134
// applications, as it defeats all standard cross-origin protection
@@ -142,24 +150,142 @@ wsServer.on('request', function(request) {
142150
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
143151
return;
144152
}
145-
153+
154+
const connection = request.accept('echo-protocol', request.origin);
155+
console.log((new Date()) + ' Connection accepted.');
156+
157+
connection.on('message', async function(message) {
158+
try {
159+
if (message.type === 'utf8') {
160+
console.log('Received Message: ' + message.utf8Data);
161+
await connection.sendUTF(message.utf8Data);
162+
}
163+
else if (message.type === 'binary') {
164+
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
165+
await connection.sendBytes(message.binaryData);
166+
}
167+
} catch (err) {
168+
console.error('Send failed:', err);
169+
}
170+
});
171+
172+
connection.on('close', function(reasonCode, description) {
173+
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
174+
});
175+
});
176+
```
177+
178+
### Using Async Iterator (v2.0+)
179+
180+
```javascript
181+
#!/usr/bin/env node
182+
const WebSocketServer = require('websocket').server;
183+
const http = require('http');
184+
185+
const server = http.createServer(function(request, response) {
186+
console.log((new Date()) + ' Received request for ' + request.url);
187+
response.writeHead(404);
188+
response.end();
189+
});
190+
server.listen(8080, function() {
191+
console.log((new Date()) + ' Server is listening on port 8080');
192+
});
193+
194+
const wsServer = new WebSocketServer({
195+
httpServer: server,
196+
autoAcceptConnections: false
197+
});
198+
199+
function originIsAllowed(origin) {
200+
return true;
201+
}
202+
203+
wsServer.on('request', function(request) {
204+
if (!originIsAllowed(request.origin)) {
205+
request.reject();
206+
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
207+
return;
208+
}
209+
210+
const connection = request.accept('echo-protocol', request.origin);
211+
console.log((new Date()) + ' Connection accepted.');
212+
213+
// Process messages using async iteration
214+
(async () => {
215+
try {
216+
for await (const message of connection.messages()) {
217+
if (message.type === 'utf8') {
218+
console.log('Received Message: ' + message.utf8Data);
219+
await connection.sendUTF(message.utf8Data);
220+
}
221+
else if (message.type === 'binary') {
222+
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
223+
await connection.sendBytes(message.binaryData);
224+
}
225+
}
226+
} catch (err) {
227+
console.error('Connection error:', err);
228+
}
229+
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
230+
})();
231+
});
232+
```
233+
234+
<details>
235+
<summary>Using Callbacks (Traditional)</summary>
236+
237+
```javascript
238+
#!/usr/bin/env node
239+
var WebSocketServer = require('websocket').server;
240+
var http = require('http');
241+
242+
var server = http.createServer(function(request, response) {
243+
console.log((new Date()) + ' Received request for ' + request.url);
244+
response.writeHead(404);
245+
response.end();
246+
});
247+
server.listen(8080, function() {
248+
console.log((new Date()) + ' Server is listening on port 8080');
249+
});
250+
251+
wsServer = new WebSocketServer({
252+
httpServer: server,
253+
autoAcceptConnections: false
254+
});
255+
256+
function originIsAllowed(origin) {
257+
return true;
258+
}
259+
260+
wsServer.on('request', function(request) {
261+
if (!originIsAllowed(request.origin)) {
262+
request.reject();
263+
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
264+
return;
265+
}
266+
146267
var connection = request.accept('echo-protocol', request.origin);
147268
console.log((new Date()) + ' Connection accepted.');
148269
connection.on('message', function(message) {
149270
if (message.type === 'utf8') {
150271
console.log('Received Message: ' + message.utf8Data);
151-
connection.sendUTF(message.utf8Data);
272+
connection.sendUTF(message.utf8Data, function(err) {
273+
if (err) console.error('Send failed:', err);
274+
});
152275
}
153276
else if (message.type === 'binary') {
154277
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
155-
connection.sendBytes(message.binaryData);
278+
connection.sendBytes(message.binaryData, function(err) {
279+
if (err) console.error('Send failed:', err);
280+
});
156281
}
157282
});
158283
connection.on('close', function(reasonCode, description) {
159284
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
160285
});
161286
});
162287
```
288+
</details>
163289

164290
Client Example
165291
--------------
@@ -168,6 +294,53 @@ This is a simple example client that will print out any utf-8 messages it receiv
168294

169295
*This code demonstrates a client in Node.js, not in the browser*
170296

297+
### Using Async/Await (v2.0+)
298+
299+
```javascript
300+
#!/usr/bin/env node
301+
const WebSocketClient = require('websocket').client;
302+
303+
const client = new WebSocketClient();
304+
305+
async function run() {
306+
try {
307+
const connection = await client.connect('ws://localhost:8080/', 'echo-protocol');
308+
console.log('WebSocket Client Connected');
309+
310+
connection.on('error', function(error) {
311+
console.log("Connection Error: " + error.toString());
312+
});
313+
314+
connection.on('close', function() {
315+
console.log('echo-protocol Connection Closed');
316+
});
317+
318+
connection.on('message', function(message) {
319+
if (message.type === 'utf8') {
320+
console.log("Received: '" + message.utf8Data + "'");
321+
}
322+
});
323+
324+
async function sendNumber() {
325+
if (connection.connected) {
326+
const number = Math.round(Math.random() * 0xFFFFFF);
327+
await connection.sendUTF(number.toString());
328+
setTimeout(sendNumber, 1000);
329+
}
330+
}
331+
sendNumber();
332+
333+
} catch (error) {
334+
console.log('Connect Error: ' + error.toString());
335+
}
336+
}
337+
338+
run();
339+
```
340+
341+
<details>
342+
<summary>Using Callbacks (Traditional)</summary>
343+
171344
```javascript
172345
#!/usr/bin/env node
173346
var WebSocketClient = require('websocket').client;
@@ -191,7 +364,7 @@ client.on('connect', function(connection) {
191364
console.log("Received: '" + message.utf8Data + "'");
192365
}
193366
});
194-
367+
195368
function sendNumber() {
196369
if (connection.connected) {
197370
var number = Math.round(Math.random() * 0xFFFFFF);
@@ -204,6 +377,7 @@ client.on('connect', function(connection) {
204377

205378
client.connect('ws://localhost:8080/', 'echo-protocol');
206379
```
380+
</details>
207381

208382
Client Example using the *W3C WebSocket API*
209383
--------------------------------------------

0 commit comments

Comments
 (0)