Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

sockjs-client

> 编程语言
Open source

WebSocket emulation - Javascript client

8.5K stars0 likes3 views
WebsiteGitHub

About

WebSocket emulation - Javascript client

SockJS-client

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:

  • SockJS-node is a SockJS server for Node.js.

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

  • SockJS-client JavaScript client library
  • SockJS-node Node.js server
  • SockJS-erlang Erlang server
  • SockJS-cyclone Python/Cyclone/Twisted server
  • SockJS-tornado Python/Tornado server
  • SockJS-twisted Python/Twisted server
  • SockJS-aiohttp Python/Aiohttp server
  • Spring Framework Java client & server
  • vert.x Java/vert.x server
  • Xitrum Scala server
  • Atmosphere Framework JavaEE Server, Play Framework, Netty, Vert.x
  • Actix SockJS Rust Server, Actix Framework

Work in progress:

  • SockJS-ruby
  • SockJS-netty
  • SockJS-gevent (SockJS-gevent fork)
  • pyramid-SockJS
  • wildcloud-websockets
  • wai-SockJS
  • SockJS-perl
  • SockJS-go
  • syp.biz.SockJS.NET - .NET port of the SockJS client

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:

xml
<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:

javascript
 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:

javascript
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://)

Browser Websockets Streaming Polling
IE 6, 7 no no jsonp-polling
IE 8, 9 (cookies=no) no xdr-streaming † xdr-polling †
IE 8, 9 (cookies=yes) no iframe-htmlfile iframe-xhr-polling
IE 10 rfc6455 xhr-streaming xhr-polling
Chrome 6-13 hixie-76 xhr-streaming xhr-polling
Chrome 14+ hybi-10 / rfc6455 xhr-streaming xhr-polling
Firefox <10 no ‡ xhr-streaming xhr-polling
Firefox 10+ hybi-10 / rfc6455 xhr-streaming xhr-polling
Safari 5.x hixie-76 xhr-streaming xhr-polling
Safari 6+ rfc6455 xhr-streaming xhr-polling
Opera 10.70+ no ‡ iframe-eventsource iframe-xhr-polling
Opera 12.10+ rfc6455 xhr-streaming xhr-polling
Konqueror no no jsonp-polling
  • †: IE 8+ supports XDomainRequest, 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:

Browser Websockets Streaming Polling
IE 8, 9 same as above iframe-htmlfile iframe-xhr-polling
Other same as above iframe-eventsource iframe-xhr-polling

Supported transports, by name

Transport References
websocket (rfc6455) rfc 6455
websocket (hixie-76) draft-hixie-thewebsocketprotocol-76
websocket (hybi-10) draft-ietf-hybi-thewebsocketprotocol-10
xhr-streaming Transport using Cross domain XHR streaming capability (readyState=3).
xdr-streaming Transport using XDomainRequest streaming capability (readyState=3).
eventsource EventSource/Server-sent events.
iframe-eventsource EventSource/Server-sent events used from an iframe via postMessage.
htmlfile HtmlFile.
iframe-htmlfile HtmlFile used from an iframe via postMessage.
xhr-polling Long-polling using cross domain XHR.
xdr-polling Long-polling using XDomainRequest.
iframe-xhr-polling Long-polling using normal AJAX from an iframe via postMessage.
jsonp-polling Slow and old fashioned JSONP polling. This transport will show "busy indicator" (aka: "spinning wheel") when sending data.

Connecting to SockJS without the client

Although the main point of

Issues· 33 open

View all issuesOpen on GitHub
  • #705

    Silent message loss when sending bulk data over the `websocket` transport (backpressure is ignored)

    Updated Sep 24, 2026
  • #681

    crypto.randombytes is not function with socket js client

    Updated May 4, 2026
  • #684

    Request: Publish v1.6.2 to npm with pagehide fix

    Updated Apr 24, 2026
  • #664

    esbuild calling an intranet URL

    Updated Nov 14, 2025
  • #257

    Support for setting withCredential true/false

    Updated May 21, 2025
  • #674

    postMEssage第二个参数存在中危漏洞

    Updated Apr 9, 2025
  • #658

    `Whoops! Lost connection to` error with npm

    Updated Aug 16, 2024
  • #657

    websocket disconnected

    Updated Aug 12, 2024
  • #625

    Sockjs Connection getting 401 error , info endpoint

    Updated Apr 4, 2024
  • #642

    Unable to detect Chromium based browsers

    Updated Mar 16, 2024

> Tags

JavaScriptjavascriptreal-timesockjswebsocket

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 30, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言