sockjs-client vs reconnecting-websocket vs @stomp/stompjs vs stompjs vs webstomp-client
WebSocket and STOMP Libraries
sockjs-clientreconnecting-websocket@stomp/stompjsstompjswebstomp-clientSimilar Packages:
WebSocket and STOMP Libraries

WebSocket and STOMP libraries in JavaScript provide tools for real-time communication between clients and servers. These libraries enable bidirectional data exchange, allowing applications to send and receive messages instantly. WebSocket libraries focus on establishing and managing WebSocket connections, while STOMP (Simple Text Oriented Messaging Protocol) libraries build on top of WebSockets to provide a messaging protocol that supports features like topics, queues, and message acknowledgments. These libraries are essential for developing chat applications, live updates, online gaming, and other real-time web applications.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
sockjs-client2,515,7278,523700 kB30-MIT
reconnecting-websocket546,8191,310-686 years agoMIT
@stomp/stompjs332,738869473 kB2418 days agoApache-2.0
stompjs48,9251,447-8812 years agoApache-2.0
webstomp-client21,992298-237 years agoApache-2.0
Feature Comparison: sockjs-client vs reconnecting-websocket vs @stomp/stompjs vs stompjs vs webstomp-client

Protocol Support

  • sockjs-client:

    sockjs-client provides a WebSocket emulation protocol with fallback options for environments where WebSockets are not supported. It ensures reliable real-time communication by automatically selecting the best available transport method, including XHR streaming, long polling, and iframe-based transports.

  • reconnecting-websocket:

    reconnecting-websocket focuses on the WebSocket protocol, providing a simple client with automatic reconnection capabilities. It does not implement any messaging protocols, making it suitable for applications that handle their own message formatting and processing.

  • @stomp/stompjs:

    @stomp/stompjs supports the STOMP protocol over WebSockets, providing a full-featured implementation with support for transactions, acknowledgments, and heartbeats. It is ideal for applications that require robust messaging capabilities and compliance with the STOMP specification.

  • stompjs:

    stompjs implements the STOMP protocol over WebSockets, providing a lightweight client for sending and receiving messages. It is suitable for applications that need basic STOMP functionality without the overhead of advanced features.

  • webstomp-client:

    webstomp-client provides a modern implementation of the STOMP protocol over WebSockets, focusing on simplicity and performance. It is designed for applications that require efficient messaging with a clean API.

Reconnection

  • sockjs-client:

    sockjs-client does not provide automatic reconnection out of the box, but it can be combined with other libraries or custom code to implement reconnection logic. Its primary focus is on providing fallback transports for real-time communication.

  • reconnecting-websocket:

    reconnecting-websocket is specifically designed for automatic reconnection, with configurable parameters for retry delays, maximum attempts, and exponential backoff. It is lightweight and easy to integrate, making it ideal for applications that need reliable WebSocket connections.

  • @stomp/stompjs:

    @stomp/stompjs includes built-in support for automatic reconnection with configurable retry intervals. It also supports heartbeats to detect and recover from lost connections, ensuring reliable communication in unstable network conditions.

  • stompjs:

    stompjs does not include built-in reconnection logic, but it can be extended to support automatic reconnection. Developers need to implement their own reconnection strategies to handle lost connections.

  • webstomp-client:

    webstomp-client does not provide automatic reconnection, but its simple API makes it easy to implement custom reconnection logic. It is designed for applications that require efficient messaging and can handle connection management externally.

Fallback Support

  • sockjs-client:

    sockjs-client is designed to provide fallback support for real-time communication in environments where WebSockets are not supported. It automatically selects the best available transport method, including XHR streaming, long polling, and iframe-based transports, ensuring reliable communication across a wide range of browsers and network conditions.

  • reconnecting-websocket:

    reconnecting-websocket does not provide fallback support for non-WebSocket environments. It is designed to work exclusively with WebSockets, relying on the browser's native WebSocket implementation for communication.

  • @stomp/stompjs:

    @stomp/stompjs focuses on WebSocket communication and does not provide built-in fallback support for environments where WebSockets are unavailable. However, it can be used in conjunction with libraries like SockJS to provide fallback transports while maintaining STOMP functionality.

  • stompjs:

    stompjs focuses on STOMP over WebSockets and does not provide fallback support for non-WebSocket environments. It relies on the underlying WebSocket connection for communication, making it unsuitable for environments where WebSockets are unavailable.

  • webstomp-client:

    webstomp-client provides a modern STOMP client implementation over WebSockets but does not include fallback mechanisms for environments where WebSockets are not supported. It is designed for applications that can rely on native WebSocket support.

Ease of Use

  • sockjs-client:

    sockjs-client provides a straightforward API for establishing real-time communication with fallback support. Its documentation includes examples that help developers understand how to use the library effectively, especially in scenarios where WebSocket support is uncertain.

  • reconnecting-websocket:

    reconnecting-websocket offers a simple and intuitive API for establishing WebSocket connections with automatic reconnection. Its lightweight design and clear documentation make it easy to integrate into projects with minimal effort.

  • @stomp/stompjs:

    @stomp/stompjs provides a comprehensive and well-documented API for working with STOMP over WebSockets. It includes examples and guides that make it easier for developers to implement messaging features, especially in applications that require advanced STOMP functionality.

  • stompjs:

    stompjs offers a simple API for working with the STOMP protocol over WebSockets. It is easy to use for basic messaging tasks, but its documentation may lack depth compared to more modern libraries, which could lead to a steeper learning curve for advanced features.

  • webstomp-client:

    webstomp-client provides a clean and modern API for STOMP messaging over WebSockets. Its focus on simplicity and performance makes it easy to use, and it includes documentation that helps developers quickly understand how to implement messaging features.

Ease of Use: Code Examples

  • sockjs-client:

    Real-Time Communication with Fallbacks using sockjs-client

    import SockJS from 'sockjs-client';
    const sock = new SockJS('http://localhost:8080/sockjs');
    sock.onopen = () => {
      console.log('Connection opened');
      sock.send('Hello, SockJS!');
    };
    sock.onmessage = (e) => {
      console.log('Received:', e.data);
    };
    sock.onclose = () => {
      console.log('Connection closed');
    };
    
  • reconnecting-websocket:

    WebSocket with Automatic Reconnection using reconnecting-websocket

    import ReconnectingWebSocket from 'reconnecting-websocket';
    const rws = new ReconnectingWebSocket('ws://localhost:8080/socket');
    rws.addEventListener('open', () => {
      console.log('Connected');
      rws.send('Hello, WebSocket!');
    });
    rws.addEventListener('message', (event) => {
      console.log('Received:', event.data);
    });
    
  • @stomp/stompjs:

    STOMP over WebSocket with @stomp/stompjs

    import { Client } from '@stomp/stompjs';
    const client = new Client({
      brokerURL: 'ws://localhost:8080/stomp',
      reconnectDelay: 5000,
      onConnect: () => {
        client.subscribe('/topic/messages', (message) => {
          console.log('Received:', message.body);
        });
        client.publish({ destination: '/app/chat', body: 'Hello, STOMP!' });
      },
    });
    client.activate();
    
  • stompjs:

    Basic STOMP Messaging with stompjs

    import Stomp from 'stompjs';
    const client = Stomp.client('ws://localhost:8080/stomp');
    client.connect({}, () => {
      client.subscribe('/topic/messages', (message) => {
        console.log('Received:', message.body);
      });
      client.send('/app/chat', {}, 'Hello, STOMP!');
    });
    
  • webstomp-client:

    Efficient STOMP Messaging with webstomp-client

    import webstomp from 'webstomp-client';
    const socket = new WebSocket('ws://localhost:8080/webstomp');
    const client = webstomp.over(socket);
    client.connect({}, () => {
      client.subscribe('/topic/messages', (message) => {
        console.log('Received:', message.body);
      });
      client.send('/app/chat', 'Hello, WebSTOMP!');
    });
    
How to Choose: sockjs-client vs reconnecting-websocket vs @stomp/stompjs vs stompjs vs webstomp-client
  • sockjs-client:

    Choose sockjs-client if you need a WebSocket emulation library that provides fallback options for environments where WebSockets are not supported. It is useful for applications that need to ensure real-time communication across a wide range of browsers and network conditions.

  • reconnecting-websocket:

    Choose reconnecting-websocket if you need a simple WebSocket client with automatic reconnection capabilities. It is lightweight and easy to use, making it suitable for applications that require reliable WebSocket connections without the overhead of a full messaging protocol.

  • @stomp/stompjs:

    Choose @stomp/stompjs if you need a modern, fully-featured STOMP client with support for WebSockets and fallback options. It is ideal for applications that require robust messaging capabilities, including support for transactions, acknowledgments, and heartbeats.

  • stompjs:

    Choose stompjs if you need a lightweight STOMP client for WebSocket communication. It is suitable for applications that require basic STOMP functionality without the need for advanced features or extensive configuration.

  • webstomp-client:

    Choose webstomp-client if you need a modern STOMP client with a focus on simplicity and performance. It is designed for applications that require efficient messaging over WebSockets with a clean and easy-to-use API.

README for sockjs-client

SockJS-client

npm versionDependenciesChatContributor Covenant BrowserStack Status

SockJS for enterprise

Available as part of the Tidelift Subscription.

The maintainers of SockJS and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Summary

SockJS is a browser JavaScript library that provides a WebSocket-like object. SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency, full duplex, cross-domain communication channel between the browser and the web server.

Under the hood SockJS tries to use native WebSockets first. If that fails it can use a variety of browser-specific transport protocols and presents them through WebSocket-like abstractions.

SockJS is intended to work for all modern browsers and in environments which don't support the WebSocket protocol -- for example, behind restrictive corporate proxies.

SockJS-client does require a server counterpart:

Philosophy:

  • The API should follow HTML5 Websockets API as closely as possible.
  • All the transports must support cross domain connections out of the box. It's possible and recommended to host a SockJS server on a different server than your main web site.
  • There is support for at least one streaming protocol for every major browser.
  • Streaming transports should work cross-domain and should support cookies (for cookie-based sticky sessions).
  • Polling transports are used as a fallback for old browsers and hosts behind restrictive proxies.
  • Connection establishment should be fast and lightweight.
  • No Flash inside (no need to open port 843 - which doesn't work through proxies, no need to host 'crossdomain.xml', no need to wait for 3 seconds in order to detect problems)

Subscribe to SockJS mailing list for discussions and support.

SockJS family

Work in progress:

Getting Started

SockJS mimics the WebSockets API, but instead of WebSocket there is a SockJS Javascript object.

First, you need to load the SockJS JavaScript library. For example, you can put that in your HTML head:

<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>

After the script is loaded you can establish a connection with the SockJS server. Here's a simple example:

 var sock = new SockJS('https://mydomain.com/my_prefix');
 sock.onopen = function() {
     console.log('open');
     sock.send('test');
 };

 sock.onmessage = function(e) {
     console.log('message', e.data);
     sock.close();
 };

 sock.onclose = function() {
     console.log('close');
 };

SockJS-client API

SockJS class

Similar to the 'WebSocket' API, the 'SockJS' constructor takes one, or more arguments:

var sockjs = new SockJS(url, _reserved, options);

url may contain a query string, if one is desired.

Where options is a hash which can contain:

  • server (string)

    String to append to url for actual data connection. Defaults to a random 4 digit number.

  • transports (string OR array of strings)

    Sometimes it is useful to disable some fallback transports. This option allows you to supply a list transports that may be used by SockJS. By default all available transports will be used.

  • sessionId (number OR function)

    Both client and server use session identifiers to distinguish connections. If you specify this option as a number, SockJS will use its random string generator function to generate session ids that are N-character long (where N corresponds to the number specified by sessionId). When you specify this option as a function, the function must return a randomly generated string. Every time SockJS needs to generate a session id it will call this function and use the returned string directly. If you don't specify this option, the default is to use the default random string generator to generate 8-character long session ids.

  • timeout (number)

    Specify a minimum timeout in milliseconds to use for the transport connections. By default this is dynamically calculated based on the measured RTT and the number of expected round trips. This setting will establish a minimum, but if the calculated timeout is higher, that will be used.

Although the 'SockJS' object tries to emulate the 'WebSocket' behaviour, it's impossible to support all of its features. An important SockJS limitation is the fact that you're not allowed to open more than one SockJS connection to a single domain at a time. This limitation is caused by an in-browser limit of outgoing connections - usually browsers don't allow opening more than two outgoing connections to a single domain. A single SockJS session requires those two connections - one for downloading data, the other for sending messages. Opening a second SockJS session at the same time would most likely block, and can result in both sessions timing out.

Opening more than one SockJS connection at a time is generally a bad practice. If you absolutely must do it, you can use multiple subdomains, using a different subdomain for every SockJS connection.

Supported transports, by browser (html served from http:// or https://)

BrowserWebsocketsStreamingPolling
IE 6, 7nonojsonp-polling
IE 8, 9 (cookies=no)noxdr-streaming †xdr-polling †
IE 8, 9 (cookies=yes)noiframe-htmlfileiframe-xhr-polling
IE 10rfc6455xhr-streamingxhr-polling
Chrome 6-13hixie-76xhr-streamingxhr-polling
Chrome 14+hybi-10 / rfc6455xhr-streamingxhr-polling
Firefox <10no ‡xhr-streamingxhr-polling
Firefox 10+hybi-10 / rfc6455xhr-streamingxhr-polling
Safari 5.xhixie-76xhr-streamingxhr-polling
Safari 6+rfc6455xhr-streamingxhr-polling
Opera 10.70+no ‡iframe-eventsourceiframe-xhr-polling
Opera 12.10+rfc6455xhr-streamingxhr-polling
Konquerornonojsonp-polling
  • : IE 8+ supports [XDomainRequest]1, which is essentially a modified AJAX/XHR that can do requests across domains. But unfortunately it doesn't send any cookies, which makes it inappropriate for deployments when the load balancer uses JSESSIONID cookie to do sticky sessions.

  • : Firefox 4.0 and Opera 11.00 and shipped with disabled Websockets "hixie-76". They can still be enabled by manually changing a browser setting.

Supported transports, by browser (html served from file://)

Sometimes you may want to serve your html from "file://" address - for development or if you're using PhoneGap or similar technologies. But due to the Cross Origin Policy files served from "file://" have no Origin, and that means some of SockJS transports won't work. For this reason the SockJS transport table is different than usually, major differences are:

BrowserWebsocketsStreamingPolling
IE 8, 9same as aboveiframe-htmlfileiframe-xhr-polling
Othersame as aboveiframe-eventsourceiframe-xhr-polling

Supported transports, by name

TransportReferences
websocket (rfc6455)[rfc 6455]2
websocket (hixie-76)[draft-hixie-thewebsocketprotocol-76]3
websocket (hybi-10)[draft-ietf-hybi-thewebsocketprotocol-10]4
xhr-streamingTransport using [Cross domain XHR]5 [streaming]6 capability (readyState=3).
xdr-streamingTransport using [XDomainRequest]1 [streaming]6 capability (readyState=3).
eventsource[EventSource/Server-sent events]7.
iframe-eventsource[EventSource/Server-sent events]7 used from an [iframe via postMessage]8.
htmlfile[HtmlFile]9.
iframe-htmlfile[HtmlFile]9 used from an [iframe via postMessage]8.
xhr-pollingLong-polling using [cross domain XHR]5.
xdr-pollingLong-polling using [XDomainRequest]1.
iframe-xhr-pollingLong-polling using normal AJAX from an [iframe via postMessage]8.
jsonp-pollingSlow and old fashioned [JSONP polling]10. This transport will show "busy indicator" (aka: "spinning wheel") when sending data.

Connecting to SockJS without the client

Although the main point of SockJS is to enable browser-to-server connectivity, it is possible to connect to SockJS from an external application. Any SockJS server complying with 0.3 protocol does support a raw WebSocket url. The raw WebSocket url for the test server looks like:

  • ws://localhost:8081/echo/websocket

You can connect any WebSocket RFC 6455 compliant WebSocket client to this url. This can be a command line client, external application, third party code or even a browser (though I don't know why you would want to do so).

Deployment

You should use a version of sockjs-client that supports the protocol used by your server. For example:

<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>

For server-side deployment tricks, especially about load balancing and session stickiness, take a look at the SockJS-node readme.

Development and testing

SockJS-client needs node.js for running a test server and JavaScript minification. If you want to work on SockJS-client source code, checkout the git repo and follow these steps:

cd sockjs-client
npm install

To generate JavaScript, run:

gulp browserify

To generate minified JavaScript, run:

gulp browserify:min

Both commands output into the build directory.

Testing

Automated testing provided by:

Once you've compiled the SockJS-client you may want to check if your changes pass all the tests.

npm run test:browser_local

This will start karma and a test support server.

Browser Quirks

There are various browser quirks which we don't intend to address:

  • Pressing ESC in Firefox, before Firefox 20, closes the SockJS connection. For a workaround and discussion see #18.
  • jsonp-polling transport will show a "spinning wheel" (aka. "busy indicator") when sending data.
  • You can't open more than one SockJS connection to one domain at the same time due to the browser's limit of concurrent connections (this limit is not counting native WebSocket connections).
  • Although SockJS is trying to escape any strange Unicode characters (even invalid ones - like surrogates \xD800-\xDBFF or \xFFFE and \xFFFF) it's advisable to use only valid characters. Using invalid characters is a bit slower, and may not work with SockJS servers that have proper Unicode support.
  • Having a global function called onmessage or such is probably a bad idea, as it could be called by the built-in postMessage API.
  • From SockJS' point of view there is nothing special about SSL/HTTPS. Connecting between unencrypted and encrypted sites should work just fine.
  • Although SockJS does its best to support both prefix and cookie based sticky sessions, the latter may not work well cross-domain with browsers that don't accept third-party cookies by default (Safari). In order to get around this make sure you're connecting to SockJS from the same parent domain as the main site. For example 'sockjs.a.com' is able to set cookies if you're connecting from 'www.a.com' or 'a.com'.
  • Trying to connect from secure "https://" to insecure "http://" is not a good idea. The other way around should be fine.
  • Long polling is known to cause problems on Heroku, but a workaround for SockJS is available.
  • SockJS websocket transport is more stable over SSL. If you're a serious SockJS user then consider using SSL (more info).

Footnotes

  1. https://blogs.msdn.microsoft.com/ieinternals/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds/ 2 3

  2. https://www.rfc-editor.org/rfc/rfc6455.txt

  3. https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76

  4. https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10

  5. https://secure.wikimedia.org/wikipedia/en/wiki/XMLHttpRequest#Cross-domain_requests 2

  6. http://www.debugtheweb.com/test/teststreaming.aspx 2

  7. https://html.spec.whatwg.org/multipage/comms.html#server-sent-events 2

  8. https://developer.mozilla.org/en/DOM/window.postMessage 2 3

  9. http://cometdaily.com/2007/11/18/ie-activexhtmlfile-transport-part-ii/ 2

  10. https://secure.wikimedia.org/wikipedia/en/wiki/JSONP