Project Icon

sockjs-client

JavaScript 实现的跨浏览器实时通信库

SockJS-client 是一个 JavaScript 库,为浏览器和 Web 服务器提供低延迟、全双工、跨域通信能力。它优先使用 WebSocket,并在不支持时自动降级到其他传输协议。该库兼容现代浏览器,并能在受限网络环境中工作。SockJS-client 需要配合服务器端实现,如 SockJS-node,共同构建实时通信应用。

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

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

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号