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.
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:
Subscribe to SockJS mailing list for discussions and support.
Work in progress:
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'); };
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.
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]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.
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 |
Transport | References |
---|---|
websocket (rfc6455) | [rfc 6455]2 |
websocket (hixie-76) | [draft-hixie-thewebsocketprotocol-76]3 |
websocket (hybi-10) | [draft-ietf-hybi-thewebsocketprotocol-10]4 |
xhr-streaming | Transport using [Cross domain XHR]5 [streaming]6 capability (readyState=3). |
xdr-streaming | Transport 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-polling | Long-polling using [cross domain XHR]5. |
xdr-polling | Long-polling using [XDomainRequest]1. |
iframe-xhr-polling | Long-polling using normal AJAX from an [iframe via postMessage]8. |
jsonp-polling | Slow and old fashioned [JSONP polling]10. This transport will show "busy indicator" (aka: "spinning wheel") when sending data. |
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:
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).
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.
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.
Automated testing provided by:
<a href="https://browserstack.com"><img src="img/Browserstack-logo@2x.png" height="50"></a>
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.
There are various browser quirks which we don't intend to address:
jsonp-polling
transport will show a "spinning wheel" (aka. "busy indicator")
when sendinghttps://blogs.msdn.microsoft.com/ieinternals/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds/ ↩ ↩2 ↩3
https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 ↩
https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 ↩
https://secure.wikimedia.org/wikipedia/en/wiki/XMLHttpRequest#Cross-domain_requests ↩ ↩2
https://html.spec.whatwg.org/multipage/comms.html#server-sent-events ↩ ↩2
https://developer.mozilla.org/en/DOM/window.postMessage ↩ ↩2 ↩3
http://cometdaily.com/2007/11/18/ie-activexhtmlfile-transport-part-ii/ ↩ ↩2
最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。
像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。
AI数字人视频创作平台
Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。
一站式AI创作平台
提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作
AI办公助手,复杂任务高效处理
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!
AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写 、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号