websocket vs reconnecting-websocket vs socket.io-client
WebSocket Libraries
websocketreconnecting-websocketsocket.io-clientSimilar Packages:

WebSocket Libraries

WebSocket libraries facilitate real-time communication between clients and servers over a single, long-lived connection. They enable developers to build applications that require instant data updates, such as chat applications, live notifications, and real-time collaboration tools. Each library offers unique features and capabilities that cater to different use cases and developer preferences, making it essential to choose the right one based on project requirements.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
websocket1,092,8143,792154 kB732 years agoApache-2.0
reconnecting-websocket01,313-686 years agoMIT
socket.io-client062,9501.42 MB2063 months agoMIT

Feature Comparison: websocket vs reconnecting-websocket vs socket.io-client

Reconnection Handling

  • websocket:

    WebSocket does not provide built-in reconnection handling. Developers must implement their own logic to handle reconnections, which can add complexity to the application. This approach offers more control but requires additional effort to ensure a reliable connection.

  • reconnecting-websocket:

    Reconnecting WebSocket automatically attempts to reconnect when the connection is lost, providing a seamless experience for users. It manages the reconnection attempts and allows developers to configure the maximum number of retries and the delay between attempts, ensuring that applications remain responsive even in unstable network conditions.

  • socket.io-client:

    Socket.IO includes built-in reconnection handling that automatically reconnects to the server when the connection is lost. It provides configurable options for reconnection attempts, delays, and backoff strategies, making it robust for real-time applications that require high availability.

Protocol Features

  • websocket:

    WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection. It is a low-level API that allows developers to send and receive messages in real-time, but it does not include higher-level features like event handling or broadcasting.

  • reconnecting-websocket:

    Reconnecting WebSocket is a wrapper around the native WebSocket API, providing additional features like automatic reconnection without altering the underlying WebSocket protocol. It maintains compatibility with existing WebSocket implementations, making it easy to integrate into existing projects.

  • socket.io-client:

    Socket.IO extends the WebSocket protocol with additional features such as event-based communication, broadcasting, and the ability to create rooms and namespaces. This makes it suitable for applications that require more than just a simple message-passing mechanism.

Browser Compatibility

  • websocket:

    WebSocket is supported in all modern browsers, but older browsers may not support it. Developers must consider the target audience and browser compatibility when using the WebSocket API.

  • reconnecting-websocket:

    Reconnecting WebSocket is compatible with modern browsers that support the WebSocket API. It does not provide fallback options for older browsers, so it is best suited for applications targeting current web standards.

  • socket.io-client:

    Socket.IO is designed to work across a wide range of browsers, including older ones. It automatically falls back to other transport methods (like long polling) if WebSocket is not available, ensuring broader compatibility for real-time applications.

Ease of Use

  • websocket:

    WebSocket has a more complex API that requires developers to manage connections, message formats, and error handling manually. While this offers flexibility, it may increase the learning curve for developers who are new to real-time communication.

  • reconnecting-websocket:

    Reconnecting WebSocket offers a simple API that enhances the native WebSocket API with minimal additional complexity. It is easy to use for developers familiar with WebSocket, making it a great choice for straightforward implementations that require reconnection capabilities.

  • socket.io-client:

    Socket.IO provides a higher-level API that abstracts many complexities of real-time communication, making it easier for developers to implement features like event handling and broadcasting. This can significantly speed up development time, especially for complex applications.

Performance

  • websocket:

    WebSocket provides the best performance for real-time communication due to its low-level nature and minimal overhead. It allows for fast message transmission and is ideal for applications that require high throughput and low latency.

  • reconnecting-websocket:

    Reconnecting WebSocket maintains performance similar to native WebSocket, but the overhead of managing reconnections may introduce slight delays during network interruptions. However, it is optimized to minimize the impact on the user experience during reconnections.

  • socket.io-client:

    Socket.IO may introduce some performance overhead due to its additional features and abstractions. However, it is optimized for real-time applications and can handle a large number of concurrent connections efficiently, making it suitable for high-load scenarios.

How to Choose: websocket vs reconnecting-websocket vs socket.io-client

  • websocket:

    Choose WebSocket if you prefer a lightweight and straightforward implementation for real-time communication without additional abstractions. It is best for applications where you want full control over the WebSocket protocol and do not need the extra features provided by other libraries.

  • reconnecting-websocket:

    Choose Reconnecting WebSocket if you need automatic reconnection capabilities for WebSocket connections, especially in scenarios where network instability is a concern. It is ideal for applications that require persistent connections and cannot afford to lose messages during disconnections.

  • socket.io-client:

    Choose Socket.IO if you require a comprehensive solution that includes fallback options for older browsers and automatic reconnection. It also offers additional features like rooms, namespaces, and event-based communication, making it suitable for complex real-time applications.

README for websocket

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.35 - Release 2024-05-12

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