Skip to content

theturtle32/WebSocket-Node

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WebSocket Client & Server Implementation for Node

npm version

NPM Downloads

Codeship Status for theturtle32/WebSocket-Node

Overview

This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder.

Documentation

You can read the full API documentation in the docs folder.

Changelog

Current Version: 1.0.34 - Release 2021-04-14

  • Updated browser shim to use the native globalThis property when available. See this MDN page for context. Resolves #415

View the full changelog

Browser Support

All current browsers are fully* supported.

  • Firefox 7-9 (Old) (Protocol Version 8)
  • Firefox 10+ (Protocol Version 13)
  • Chrome 14,15 (Old) (Protocol Version 8)
  • Chrome 16+ (Protocol Version 13)
  • Internet Explorer 10+ (Protocol Version 13)
  • Safari 6+ (Protocol Version 13)

(Not all W3C WebSocket features are supported by browsers. More info in the Full API documentation)

Benchmarks

There are some basic benchmarking sections in the Autobahn test suite. I've put up a benchmark page that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4.

(These benchmarks are quite a bit outdated at this point, so take them with a grain of salt. Anyone up for running new benchmarks? I'll link to your report.)

Autobahn Tests

The very complete Autobahn Test Suite is used by most WebSocket implementations to test spec compliance and interoperability.

Installation

In your project root:

$ npm install websocket 

Then in your code:

const WebSocketServer = require('websocket').server; const WebSocketClient = require('websocket').client; const WebSocketFrame = require('websocket').frame; const WebSocketRouter = require('websocket').router; const W3CWebSocket = require('websocket').w3cwebsocket;

Current Features:

  • Licensed under the Apache License, Version 2.0
  • Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake
  • Can handle/aggregate received fragmented messages
  • Can fragment outgoing messages
  • Router to mount multiple applications to various path and protocol combinations
  • TLS supported for outbound connections via WebSocketClient
  • TLS supported for server connections (use https.createServer instead of http.createServer)
    • Thanks to pors for confirming this!
  • Promise-based API (v2.0+) - All async operations support both callbacks and Promises
    • client.connect() returns a Promise
    • connection.send(), sendUTF(), sendBytes() return Promises when no callback provided
    • connection.close() returns a Promise
    • connection.messages() async iterator for consuming messages
    • Fully backward compatible - existing callback-based code works unchanged
  • Cookie setting and parsing
  • Tunable settings
    • Max Receivable Frame Size
    • Max Aggregate ReceivedMessage Size
    • Whether to fragment outgoing messages
    • Fragmentation chunk size for outgoing messages
    • Whether to automatically send ping frames for the purposes of keepalive
    • Keep-alive ping interval
    • Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)
    • How long to wait after sending a close frame for acknowledgment before closing the socket.
  • W3C WebSocket API for applications running on both Node and browsers (via the W3CWebSocket class).

Known Issues/Missing Features:

  • No API for user-provided protocol extensions.

Usage Examples

Server Example

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

Using Async/Await with Event Handlers (v2.0+)

#!/usr/bin/env node const WebSocketServer = require('websocket').server; const http = require('http'); const server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); const wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } const connection = request.accept('echo-protocol', request.origin); console.log((new Date()) + ' Connection accepted.'); connection.on('message', async function(message) { try { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); await connection.sendUTF(message.utf8Data); } else if (message.type === 'binary') { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); await connection.sendBytes(message.binaryData); } } catch (err) { console.error('Send failed:', err); } }); connection.on('close', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); });

Using Async Iterator (v2.0+)

#!/usr/bin/env node const WebSocketServer = require('websocket').server; const http = require('http'); const server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); const wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); function originIsAllowed(origin) { return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } const connection = request.accept('echo-protocol', request.origin); console.log((new Date()) + ' Connection accepted.'); // Process messages using async iteration (async () => { try { for await (const message of connection.messages()) { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); await connection.sendUTF(message.utf8Data); } else if (message.type === 'binary') { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); await connection.sendBytes(message.binaryData); } } } catch (err) { console.error('Connection error:', err); } console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); })(); });
Using Callbacks (Traditional)
#!/usr/bin/env node const WebSocketServer = require('websocket').server; const http = require('http'); const server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); const wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); function originIsAllowed(origin) { return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } const connection = request.accept('echo-protocol', request.origin); console.log((new Date()) + ' Connection accepted.'); connection.on('message', function(message) { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); connection.sendUTF(message.utf8Data, function(err) { if (err) console.error('Send failed:', err); }); } else if (message.type === 'binary') { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); connection.sendBytes(message.binaryData, function(err) { if (err) console.error('Send failed:', err); }); } }); connection.on('close', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); });

Client Example

This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.

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

Using Async/Await (v2.0+)

#!/usr/bin/env node const WebSocketClient = require('websocket').client; const client = new WebSocketClient(); async function run() { try { const connection = await client.connect('ws://localhost:8080/', 'echo-protocol'); console.log('WebSocket Client Connected'); connection.on('error', function(error) { console.log("Connection Error: " + error.toString()); }); connection.on('message', function(message) { if (message.type === 'utf8') { console.log("Received: '" + message.utf8Data + "'"); } }); // Send a random number every second let timeoutId; (async function sendNumber() { if (connection.connected) { const number = Math.round(Math.random() * 0xFFFFFF); await connection.sendUTF(number.toString()); timeoutId = setTimeout(sendNumber, 1000); } })(); connection.on('close', function() { clearTimeout(timeoutId); console.log('echo-protocol Connection Closed'); }); } catch (error) { console.log('Connect Error: ' + error.toString()); } } run();
Using Callbacks (Traditional)
#!/usr/bin/env node const WebSocketClient = require('websocket').client; const client = new WebSocketClient(); client.on('connectFailed', function(error) { console.log('Connect Error: ' + error.toString()); }); client.on('connect', function(connection) { console.log('WebSocket Client Connected'); connection.on('error', function(error) { console.log("Connection Error: " + error.toString()); }); connection.on('message', function(message) { if (message.type === 'utf8') { console.log("Received: '" + message.utf8Data + "'"); } }); // Send a random number every second const interval = setInterval(function() { if (connection.connected) { const number = Math.round(Math.random() * 0xFFFFFF); connection.sendUTF(number.toString()); } }, 1000); connection.on('close', function() { clearInterval(interval); console.log('echo-protocol Connection Closed'); }); }); client.connect('ws://localhost:8080/', 'echo-protocol');

Client Example using the W3C WebSocket API

Same example as above but using the W3C WebSocket API.

const W3CWebSocket = require('websocket').w3cwebsocket; const client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol'); client.onerror = function() { console.log('Connection Error'); }; client.onopen = function() { console.log('WebSocket Client Connected'); // Send a random number every second const interval = setInterval(function() { if (client.readyState === client.OPEN) { const number = Math.round(Math.random() * 0xFFFFFF); client.send(number.toString()); } }, 1000); // Clear interval when connection closes client.onclose = function() { clearInterval(interval); console.log('echo-protocol Client Closed'); }; }; client.onmessage = function(e) { if (typeof e.data === 'string') { console.log("Received: '" + e.data + "'"); } };

Request Router Example

For an example of using the request router, see libwebsockets-test-server.js in the test folder.

Development & Contributing

v2.0 Modernization Project

WebSocket-Node is currently undergoing a comprehensive modernization for v2.0, which includes:

  • βœ… ES6 Classes - All components converted to ES6 class syntax
  • βœ… Modern JavaScript - Template literals, arrow functions, destructuring, etc.
  • βœ… Promise-based APIs - All async operations support Promises (fully backward compatible)
  • πŸ”„ Comprehensive Test Suite - Migrating to Vitest with extensive coverage (in progress)

Current Status: 65% Complete

For detailed information:

Running Tests

# Install dependencies pnpm install # Run all tests pnpm test # Run tests in watch mode pnpm test:watch # Run tests with coverage pnpm test:coverage # Run protocol compliance tests pnpm test:autobahn # Run linter pnpm lint # Fix lint issues pnpm lint:fix

Test Coverage

Current coverage: 68% overall (target: 85%+)

Component Coverage Status
WebSocketRouter 98.71% βœ… Complete
WebSocketServer 92.36% βœ… Complete
WebSocketFrame 92.47% βœ… Complete
WebSocketClient 88.31% βœ… Complete
WebSocketConnection 71.48% πŸ”„ In Progress
WebSocketRequest 29.63% ⚠️ Needs Work

Contributing

Contributions are welcome! For the v2.0 modernization:

  1. Check current work in ROADMAP.md
  2. Review V2_MODERNIZATION_STATUS.md for status
  3. Work from the v2 branch
  4. Create feature branches for your work
  5. Run pnpm test && pnpm lint before submitting PRs
  6. Maintain backward compatibility for all public APIs

Resources

A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. WebSockets: The Real-Time Web, Delivered

About

A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

Resources

License

Stars

Watchers

Forks

Packages

No packages published