PageRenderTime 176ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/ws/README.md

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