You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

449 lines
13 KiB

4 years ago
  1. # ws: a Node.js WebSocket library
  2. [![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws)
  3. [![Linux Build](https://img.shields.io/travis/websockets/ws/master.svg?logo=travis)](https://travis-ci.org/websockets/ws)
  4. [![Windows Build](https://img.shields.io/appveyor/ci/lpinca/ws/master.svg?logo=appveyor)](https://ci.appveyor.com/project/lpinca/ws)
  5. [![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/github/websockets/ws)
  6. ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
  7. server implementation.
  8. Passes the quite extensive Autobahn test suite: [server][server-report],
  9. [client][client-report].
  10. **Note**: This module does not work in the browser. The client in the docs is a
  11. reference to a back end with the role of a client in the WebSocket
  12. communication. Browser clients must use the native
  13. [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
  14. object. To make the same code work seamlessly on Node.js and the browser, you
  15. can use one of the many wrappers available on npm, like
  16. [isomorphic-ws](https://github.com/heineiuo/isomorphic-ws).
  17. ## Table of Contents
  18. - [Protocol support](#protocol-support)
  19. - [Installing](#installing)
  20. - [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance)
  21. - [API docs](#api-docs)
  22. - [WebSocket compression](#websocket-compression)
  23. - [Usage examples](#usage-examples)
  24. - [Sending and receiving text data](#sending-and-receiving-text-data)
  25. - [Sending binary data](#sending-binary-data)
  26. - [Simple server](#simple-server)
  27. - [External HTTP/S server](#external-https-server)
  28. - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server)
  29. - [Server broadcast](#server-broadcast)
  30. - [echo.websocket.org demo](#echowebsocketorg-demo)
  31. - [Other examples](#other-examples)
  32. - [Error handling best practices](#error-handling-best-practices)
  33. - [FAQ](#faq)
  34. - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client)
  35. - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections)
  36. - [How to connect via a proxy?](#how-to-connect-via-a-proxy)
  37. - [Changelog](#changelog)
  38. - [License](#license)
  39. ## Protocol support
  40. - **HyBi drafts 07-12** (Use the option `protocolVersion: 8`)
  41. - **HyBi drafts 13-17** (Current default, alternatively option
  42. `protocolVersion: 13`)
  43. ## Installing
  44. ```
  45. npm install ws
  46. ```
  47. ### Opt-in for performance and spec compliance
  48. There are 2 optional modules that can be installed along side with the ws
  49. module. These modules are binary addons which improve certain operations.
  50. Prebuilt binaries are available for the most popular platforms so you don't
  51. necessarily need to have a C++ compiler installed on your machine.
  52. - `npm install --save-optional bufferutil`: Allows to efficiently perform
  53. operations such as masking and unmasking the data payload of the WebSocket
  54. frames.
  55. - `npm install --save-optional utf-8-validate`: Allows to efficiently check if a
  56. message contains valid UTF-8 as required by the spec.
  57. ## API docs
  58. See [`/doc/ws.md`](./doc/ws.md) for Node.js-like docs for the ws classes.
  59. ## WebSocket compression
  60. ws supports the [permessage-deflate extension][permessage-deflate] which enables
  61. the client and server to negotiate a compression algorithm and its parameters,
  62. and then selectively apply it to the data payloads of each WebSocket message.
  63. The extension is disabled by default on the server and enabled by default on the
  64. client. It adds a significant overhead in terms of performance and memory
  65. consumption so we suggest to enable it only if it is really needed.
  66. Note that Node.js has a variety of issues with high-performance compression,
  67. where increased concurrency, especially on Linux, can lead to [catastrophic
  68. memory fragmentation][node-zlib-bug] and slow performance. If you intend to use
  69. permessage-deflate in production, it is worthwhile to set up a test
  70. representative of your workload and ensure Node.js/zlib will handle it with
  71. acceptable performance and memory usage.
  72. Tuning of permessage-deflate can be done via the options defined below. You can
  73. also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly
  74. into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs].
  75. See [the docs][ws-server-options] for more options.
  76. ```js
  77. const WebSocket = require('ws');
  78. const wss = new WebSocket.Server({
  79. port: 8080,
  80. perMessageDeflate: {
  81. zlibDeflateOptions: {
  82. // See zlib defaults.
  83. chunkSize: 1024,
  84. memLevel: 7,
  85. level: 3
  86. },
  87. zlibInflateOptions: {
  88. chunkSize: 10 * 1024
  89. },
  90. // Other options settable:
  91. clientNoContextTakeover: true, // Defaults to negotiated value.
  92. serverNoContextTakeover: true, // Defaults to negotiated value.
  93. serverMaxWindowBits: 10, // Defaults to negotiated value.
  94. // Below options specified as default values.
  95. concurrencyLimit: 10, // Limits zlib concurrency for perf.
  96. threshold: 1024 // Size (in bytes) below which messages
  97. // should not be compressed.
  98. }
  99. });
  100. ```
  101. The client will only use the extension if it is supported and enabled on the
  102. server. To always disable the extension on the client set the
  103. `perMessageDeflate` option to `false`.
  104. ```js
  105. const WebSocket = require('ws');
  106. const ws = new WebSocket('ws://www.host.com/path', {
  107. perMessageDeflate: false
  108. });
  109. ```
  110. ## Usage examples
  111. ### Sending and receiving text data
  112. ```js
  113. const WebSocket = require('ws');
  114. const ws = new WebSocket('ws://www.host.com/path');
  115. ws.on('open', function open() {
  116. ws.send('something');
  117. });
  118. ws.on('message', function incoming(data) {
  119. console.log(data);
  120. });
  121. ```
  122. ### Sending binary data
  123. ```js
  124. const WebSocket = require('ws');
  125. const ws = new WebSocket('ws://www.host.com/path');
  126. ws.on('open', function open() {
  127. const array = new Float32Array(5);
  128. for (var i = 0; i < array.length; ++i) {
  129. array[i] = i / 2;
  130. }
  131. ws.send(array);
  132. });
  133. ```
  134. ### Simple server
  135. ```js
  136. const WebSocket = require('ws');
  137. const wss = new WebSocket.Server({ port: 8080 });
  138. wss.on('connection', function connection(ws) {
  139. ws.on('message', function incoming(message) {
  140. console.log('received: %s', message);
  141. });
  142. ws.send('something');
  143. });
  144. ```
  145. ### External HTTP/S server
  146. ```js
  147. const fs = require('fs');
  148. const https = require('https');
  149. const WebSocket = require('ws');
  150. const server = new https.createServer({
  151. cert: fs.readFileSync('/path/to/cert.pem'),
  152. key: fs.readFileSync('/path/to/key.pem')
  153. });
  154. const wss = new WebSocket.Server({ server });
  155. wss.on('connection', function connection(ws) {
  156. ws.on('message', function incoming(message) {
  157. console.log('received: %s', message);
  158. });
  159. ws.send('something');
  160. });
  161. server.listen(8080);
  162. ```
  163. ### Multiple servers sharing a single HTTP/S server
  164. ```js
  165. const http = require('http');
  166. const WebSocket = require('ws');
  167. const server = http.createServer();
  168. const wss1 = new WebSocket.Server({ noServer: true });
  169. const wss2 = new WebSocket.Server({ noServer: true });
  170. wss1.on('connection', function connection(ws) {
  171. // ...
  172. });
  173. wss2.on('connection', function connection(ws) {
  174. // ...
  175. });
  176. server.on('upgrade', function upgrade(request, socket, head) {
  177. const pathname = url.parse(request.url).pathname;
  178. if (pathname === '/foo') {
  179. wss1.handleUpgrade(request, socket, head, function done(ws) {
  180. wss1.emit('connection', ws, request);
  181. });
  182. } else if (pathname === '/bar') {
  183. wss2.handleUpgrade(request, socket, head, function done(ws) {
  184. wss2.emit('connection', ws, request);
  185. });
  186. } else {
  187. socket.destroy();
  188. }
  189. });
  190. server.listen(8080);
  191. ```
  192. ### Server broadcast
  193. ```js
  194. const WebSocket = require('ws');
  195. const wss = new WebSocket.Server({ port: 8080 });
  196. // Broadcast to all.
  197. wss.broadcast = function broadcast(data) {
  198. wss.clients.forEach(function each(client) {
  199. if (client.readyState === WebSocket.OPEN) {
  200. client.send(data);
  201. }
  202. });
  203. };
  204. wss.on('connection', function connection(ws) {
  205. ws.on('message', function incoming(data) {
  206. // Broadcast to everyone else.
  207. wss.clients.forEach(function each(client) {
  208. if (client !== ws && client.readyState === WebSocket.OPEN) {
  209. client.send(data);
  210. }
  211. });
  212. });
  213. });
  214. ```
  215. ### echo.websocket.org demo
  216. ```js
  217. const WebSocket = require('ws');
  218. const ws = new WebSocket('wss://echo.websocket.org/', {
  219. origin: 'https://websocket.org'
  220. });
  221. ws.on('open', function open() {
  222. console.log('connected');
  223. ws.send(Date.now());
  224. });
  225. ws.on('close', function close() {
  226. console.log('disconnected');
  227. });
  228. ws.on('message', function incoming(data) {
  229. console.log(`Roundtrip time: ${Date.now() - data} ms`);
  230. setTimeout(function timeout() {
  231. ws.send(Date.now());
  232. }, 500);
  233. });
  234. ```
  235. ### Other examples
  236. For a full example with a browser client communicating with a ws server, see the
  237. examples folder.
  238. Otherwise, see the test cases.
  239. ## Error handling best practices
  240. ```js
  241. // If the WebSocket is closed before the following send is attempted
  242. ws.send('something');
  243. // Errors (both immediate and async write errors) can be detected in an optional
  244. // callback. The callback is also the only way of being notified that data has
  245. // actually been sent.
  246. ws.send('something', function ack(error) {
  247. // If error is not defined, the send has been completed, otherwise the error
  248. // object will indicate what failed.
  249. });
  250. // Immediate errors can also be handled with `try...catch`, but **note** that
  251. // since sends are inherently asynchronous, socket write failures will *not* be
  252. // captured when this technique is used.
  253. try {
  254. ws.send('something');
  255. } catch (e) {
  256. /* handle error */
  257. }
  258. ```
  259. ## FAQ
  260. ### How to get the IP address of the client?
  261. The remote IP address can be obtained from the raw socket.
  262. ```js
  263. const WebSocket = require('ws');
  264. const wss = new WebSocket.Server({ port: 8080 });
  265. wss.on('connection', function connection(ws, req) {
  266. const ip = req.connection.remoteAddress;
  267. });
  268. ```
  269. When the server runs behind a proxy like NGINX, the de-facto standard is to use
  270. the `X-Forwarded-For` header.
  271. ```js
  272. wss.on('connection', function connection(ws, req) {
  273. const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
  274. });
  275. ```
  276. ### How to detect and close broken connections?
  277. Sometimes the link between the server and the client can be interrupted in a way
  278. that keeps both the server and the client unaware of the broken state of the
  279. connection (e.g. when pulling the cord).
  280. In these cases ping messages can be used as a means to verify that the remote
  281. endpoint is still responsive.
  282. ```js
  283. const WebSocket = require('ws');
  284. function noop() {}
  285. function heartbeat() {
  286. this.isAlive = true;
  287. }
  288. const wss = new WebSocket.Server({ port: 8080 });
  289. wss.on('connection', function connection(ws) {
  290. ws.isAlive = true;
  291. ws.on('pong', heartbeat);
  292. });
  293. const interval = setInterval(function ping() {
  294. wss.clients.forEach(function each(ws) {
  295. if (ws.isAlive === false) return ws.terminate();
  296. ws.isAlive = false;
  297. ws.ping(noop);
  298. });
  299. }, 30000);
  300. ```
  301. Pong messages are automatically sent in response to ping messages as required by
  302. the spec.
  303. Just like the server example above your clients might as well lose connection
  304. without knowing it. You might want to add a ping listener on your clients to
  305. prevent that. A simple implementation would be:
  306. ```js
  307. const WebSocket = require('ws');
  308. function heartbeat() {
  309. clearTimeout(this.pingTimeout);
  310. // Use `WebSocket#terminate()` and not `WebSocket#close()`. Delay should be
  311. // equal to the interval at which your server sends out pings plus a
  312. // conservative assumption of the latency.
  313. this.pingTimeout = setTimeout(() => {
  314. this.terminate();
  315. }, 30000 + 1000);
  316. }
  317. const client = new WebSocket('wss://echo.websocket.org/');
  318. client.on('open', heartbeat);
  319. client.on('ping', heartbeat);
  320. client.on('close', function clear() {
  321. clearTimeout(this.pingTimeout);
  322. });
  323. ```
  324. ### How to connect via a proxy?
  325. Use a custom `http.Agent` implementation like [https-proxy-agent][] or
  326. [socks-proxy-agent][].
  327. ## Changelog
  328. We're using the GitHub [releases][changelog] for changelog entries.
  329. ## License
  330. [MIT](LICENSE)
  331. [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
  332. [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
  333. [client-report]: http://websockets.github.io/ws/autobahn/clients/
  334. [server-report]: http://websockets.github.io/ws/autobahn/servers/
  335. [permessage-deflate]: https://tools.ietf.org/html/rfc7692
  336. [changelog]: https://github.com/websockets/ws/releases
  337. [node-zlib-bug]: https://github.com/nodejs/node/issues/8871
  338. [node-zlib-deflaterawdocs]:
  339. https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options
  340. [ws-server-options]:
  341. https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback