Convert Figma logo to code with AI

theturtle32 logoWebSocket-Node

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

3,742
604
3,742
70

Top Related Projects

21,534

Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

60,879

Realtime application framework (Node.JS server)

Simple, secure & standards compliant web server for the most demanding of applications

22,033

Package gorilla/websocket is a fast, well-tested and widely used WebSocket implementation for Go.

WebSocket emulation - Node.js server

Quick Overview

WebSocket-Node is a robust WebSocket client and server implementation for Node.js. It provides a complete and standards-compliant WebSocket solution, supporting the latest protocol versions and offering both low-level and high-level APIs for developers to work with WebSocket connections.

Pros

  • Full compliance with the latest WebSocket protocol standards
  • Supports both client and server implementations
  • Offers both low-level and high-level APIs for flexibility
  • Well-maintained and actively developed

Cons

  • Limited built-in support for older browser versions
  • May require additional configuration for complex use cases
  • Learning curve for developers new to WebSocket technology
  • Performance may be impacted in high-concurrency scenarios

Code Examples

  1. Creating a WebSocket server:
const WebSocketServer = require('websocket').server;
const http = require('http');

const server = http.createServer();
server.listen(8080);

const wsServer = new WebSocketServer({
    httpServer: server
});

wsServer.on('request', (request) => {
    const connection = request.accept(null, request.origin);
    console.log('Connection accepted.');
});
  1. Sending a message from server to client:
connection.on('message', (message) => {
    if (message.type === 'utf8') {
        console.log('Received Message: ' + message.utf8Data);
        connection.sendUTF('Hello, Client!');
    }
});
  1. Creating a WebSocket client:
const WebSocketClient = require('websocket').client;

const client = new WebSocketClient();

client.on('connectFailed', (error) => {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', (connection) => {
    console.log('WebSocket Client Connected');
    connection.on('message', (message) => {
        if (message.type === 'utf8') {
            console.log("Received: '" + message.utf8Data + "'");
        }
    });
});

client.connect('ws://localhost:8080/');

Getting Started

To use WebSocket-Node in your project:

  1. Install the package:

    npm install websocket
    
  2. Import the necessary components:

    const WebSocketServer = require('websocket').server;
    const WebSocketClient = require('websocket').client;
    
  3. Create a server or client instance as shown in the code examples above.

  4. Implement event handlers for connection, message, and error events to manage WebSocket communication.

Competitor Comparisons

21,534

Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

Pros of ws

  • Higher performance and lower memory footprint
  • More active development and frequent updates
  • Simpler API and easier to use for basic WebSocket functionality

Cons of ws

  • Less built-in features compared to WebSocket-Node
  • May require additional modules for advanced functionality
  • Limited browser support (primarily for Node.js environments)

Code Comparison

WebSocket-Node:

const WebSocketClient = require('websocket').client;
const client = new WebSocketClient();

client.on('connect', (connection) => {
  connection.on('message', (message) => {
    console.log('Received: ' + message.utf8Data);
  });
});

client.connect('ws://localhost:8080/');

ws:

const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080/');

ws.on('open', () => {
  ws.on('message', (data) => {
    console.log('Received: ' + data);
  });
});

Both libraries provide similar functionality for creating WebSocket connections, but ws offers a more streamlined API. WebSocket-Node provides a more comprehensive set of features out of the box, while ws focuses on core WebSocket functionality with better performance.

The choice between these libraries depends on specific project requirements, such as performance needs, feature set, and target environment. ws is generally preferred for Node.js applications due to its simplicity and performance, while WebSocket-Node may be more suitable for projects requiring additional built-in features or broader browser support.

60,879

Realtime application framework (Node.JS server)

Pros of Socket.IO

  • Provides a higher-level abstraction with additional features like automatic reconnection and room support
  • Offers fallback options for environments where WebSocket is not supported
  • Has a larger ecosystem and community, with more plugins and integrations available

Cons of Socket.IO

  • Larger bundle size and potentially higher overhead due to additional features
  • May introduce unnecessary complexity for simple WebSocket use cases
  • Less flexible for custom protocol implementations or low-level WebSocket control

Code Comparison

Socket.IO server:

const io = require('socket.io')(3000);
io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
  });
});

WebSocket-Node server:

const WebSocketServer = require('websocket').server;
const server = new WebSocketServer({httpServer: httpServer});
server.on('request', (request) => {
  const connection = request.accept(null, request.origin);
  connection.on('message', (message) => {
    // Handle message
  });
});

Both libraries provide WebSocket functionality, but Socket.IO offers a more feature-rich experience at the cost of simplicity. WebSocket-Node provides a lower-level implementation, giving developers more control over the WebSocket protocol. The choice between the two depends on the specific requirements of the project, such as the need for additional features, fallback options, or low-level control.

Simple, secure & standards compliant web server for the most demanding of applications

Pros of uWebSockets

  • Higher performance and lower latency
  • Better scalability for handling large numbers of concurrent connections
  • Supports both WebSocket and HTTP protocols

Cons of uWebSockets

  • Less mature and potentially less stable than WebSocket-Node
  • Steeper learning curve due to its low-level nature
  • Limited documentation compared to WebSocket-Node

Code Comparison

WebSocket-Node:

const WebSocketServer = require('websocket').server;
const server = new WebSocketServer({
  httpServer: httpServer,
  autoAcceptConnections: false
});

uWebSockets:

#include <uwebsockets/App.h>

uWS::App().ws<PerSocketData>("/*", {
  .open = [](auto *ws, auto *req) {
    // Handle new WebSocket connection
  }
}).listen(9001, [](auto *listen_socket) {
  if (listen_socket) {
    std::cout << "Listening on port " << 9001 << std::endl;
  }
});

Summary

uWebSockets offers superior performance and scalability, making it ideal for high-traffic applications. However, it may require more expertise to implement and has less comprehensive documentation. WebSocket-Node, while potentially slower, provides a more user-friendly experience with better documentation and stability. The choice between the two depends on specific project requirements and developer expertise.

22,033

Package gorilla/websocket is a fast, well-tested and widely used WebSocket implementation for Go.

Pros of gorilla/websocket

  • Written in Go, offering better performance and concurrency
  • Simpler API with less overhead
  • More actively maintained with frequent updates

Cons of gorilla/websocket

  • Limited to Go applications, unlike WebSocket-Node's JavaScript compatibility
  • Fewer built-in features compared to WebSocket-Node's extensive functionality
  • Steeper learning curve for developers not familiar with Go

Code Comparison

WebSocket-Node:

const WebSocketServer = require('websocket').server;
const server = new WebSocketServer({
  httpServer: httpServer,
  autoAcceptConnections: false
});

gorilla/websocket:

var upgrader = websocket.Upgrader{}
func handler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        return
    }
    defer conn.Close()
}

Both libraries provide straightforward ways to create WebSocket servers, but gorilla/websocket's implementation is more concise and integrated with Go's HTTP package. WebSocket-Node offers more configuration options out of the box, while gorilla/websocket favors simplicity and relies on Go's standard library for additional functionality.

WebSocket emulation - Node.js server

Pros of SockJS-node

  • Provides fallback options for environments without WebSocket support
  • Offers a consistent API across different transport mechanisms
  • Supports multiple server implementations (Node.js, Express, etc.)

Cons of SockJS-node

  • Higher complexity due to multiple transport options
  • Slightly larger footprint compared to pure WebSocket implementations
  • May introduce additional latency in some fallback scenarios

Code Comparison

WebSocket-Node:

const WebSocketServer = require('websocket').server;
const server = new WebSocketServer({
    httpServer: httpServer,
    autoAcceptConnections: false
});

SockJS-node:

const sockjs = require('sockjs');
const sockServer = sockjs.createServer();
sockServer.on('connection', function(conn) {
    conn.on('data', function(message) {
        conn.write(message);
    });
});

Summary

WebSocket-Node is a pure WebSocket implementation for Node.js, offering a straightforward approach for WebSocket communication. SockJS-node, on the other hand, provides a more versatile solution with fallback options for environments lacking WebSocket support. While SockJS-node offers greater compatibility, it comes at the cost of increased complexity and potential performance overhead. The choice between the two depends on specific project requirements, such as browser compatibility needs and performance considerations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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:

var WebSocketServer = require('websocket').server;
var WebSocketClient = require('websocket').client;
var WebSocketFrame  = require('websocket').frame;
var WebSocketRouter = require('websocket').router;
var 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!
  • 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.

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var 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');
});

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;
    }
    
    var 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);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    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

#!/usr/bin/env node
var WebSocketClient = require('websocket').client;

var 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('close', function() {
        console.log('echo-protocol Connection Closed');
    });
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log("Received: '" + message.utf8Data + "'");
        }
    });
    
    function sendNumber() {
        if (connection.connected) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            connection.sendUTF(number.toString());
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
});

client.connect('ws://localhost:8080/', 'echo-protocol');

Client Example using the W3C WebSocket API

Same example as above but using the W3C WebSocket API.

var W3CWebSocket = require('websocket').w3cwebsocket;

var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');

client.onerror = function() {
    console.log('Connection Error');
};

client.onopen = function() {
    console.log('WebSocket Client Connected');

    function sendNumber() {
        if (client.readyState === client.OPEN) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            client.send(number.toString());
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
};

client.onclose = function() {
    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.

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

NPM DownloadsLast 30 Days