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.

496 lines
14 KiB

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