ws

Simple to use, blazing fast and thoroughly tested WebSocket client and serv...

README

ws: a Node.js WebSocket library

Version npm CI Coverage Status

ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
server implementation.

Passes the quite extensive Autobahn test suite: [server][server-report],
[client][client-report].

Note: This module does not work in the browser. The client in the docs is a
reference to a back end with the role of a client in the WebSocket
communication. Browser clients must use the native
[WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
object. To make the same code work seamlessly on Node.js and the browser, you
can use one of the many wrappers available on npm, like

Table of Contents


- FAQ

Protocol support


- HyBi drafts 07-12 (Use the option protocolVersion: 8)
- HyBi drafts 13-17 (Current default, alternatively option
  protocolVersion: 13)

Installing


  1. ```
  2. npm install ws
  3. ```

Opt-in for performance


There are 2 optional modules that can be installed along side with the ws
module. These modules are binary addons which improve certain operations.
Prebuilt binaries are available for the most popular platforms so you don't
necessarily need to have a C++ compiler installed on your machine.

- npm install --save-optional bufferutil: Allows to efficiently perform
  operations such as masking and unmasking the data payload of the WebSocket
  frames.
- npm install --save-optional utf-8-validate: Allows to efficiently check if a
  message contains valid UTF-8.

To not even try to require and use these modules, use the
[WS_NO_BUFFER_UTIL](./doc/ws.md#ws_no_buffer_util) and
[WS_NO_UTF_8_VALIDATE](./doc/ws.md#ws_no_utf_8_validate) environment
variables. These might be useful to enhance security in systems where a user can
put a package in the package search path of an application of another user, due
to how the Node.js resolver algorithm works.

API docs


See [/doc/ws.md](./doc/ws.md) for Node.js-like documentation of ws classes and
utility functions.

WebSocket compression


ws supports the [permessage-deflate extension][permessage-deflate] which enables
the client and server to negotiate a compression algorithm and its parameters,
and then selectively apply it to the data payloads of each WebSocket message.

The extension is disabled by default on the server and enabled by default on the
client. It adds a significant overhead in terms of performance and memory
consumption so we suggest to enable it only if it is really needed.

Note that Node.js has a variety of issues with high-performance compression,
where increased concurrency, especially on Linux, can lead to [catastrophic
memory fragmentation][node-zlib-bug] and slow performance. If you intend to use
permessage-deflate in production, it is worthwhile to set up a test
representative of your workload and ensure Node.js/zlib will handle it with
acceptable performance and memory usage.

Tuning of permessage-deflate can be done via the options defined below. You can
also use zlibDeflateOptions and zlibInflateOptions, which is passed directly
into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs].

See [the docs][ws-server-options] for more options.

  1. ``` js
  2. import WebSocket, { WebSocketServer } from 'ws';

  3. const wss = new WebSocketServer({
  4.   port: 8080,
  5.   perMessageDeflate: {
  6.     zlibDeflateOptions: {
  7.       // See zlib defaults.
  8.       chunkSize: 1024,
  9.       memLevel: 7,
  10.       level: 3
  11.     },
  12.     zlibInflateOptions: {
  13.       chunkSize: 10 * 1024
  14.     },
  15.     // Other options settable:
  16.     clientNoContextTakeover: true, // Defaults to negotiated value.
  17.     serverNoContextTakeover: true, // Defaults to negotiated value.
  18.     serverMaxWindowBits: 10, // Defaults to negotiated value.
  19.     // Below options specified as default values.
  20.     concurrencyLimit: 10, // Limits zlib concurrency for perf.
  21.     threshold: 1024 // Size (in bytes) below which messages
  22.     // should not be compressed if context takeover is disabled.
  23.   }
  24. });
  25. ```

The client will only use the extension if it is supported and enabled on the
server. To always disable the extension on the client set the
perMessageDeflate option to false.

  1. ``` js
  2. import WebSocket from 'ws';

  3. const ws = new WebSocket('ws://www.host.com/path', {
  4.   perMessageDeflate: false
  5. });
  6. ```

Usage examples


Sending and receiving text data


  1. ``` js
  2. import WebSocket from 'ws';

  3. const ws = new WebSocket('ws://www.host.com/path');

  4. ws.on('open', function open() {
  5.   ws.send('something');
  6. });

  7. ws.on('message', function message(data) {
  8.   console.log('received: %s', data);
  9. });
  10. ```

Sending binary data


  1. ``` js
  2. import WebSocket from 'ws';

  3. const ws = new WebSocket('ws://www.host.com/path');

  4. ws.on('open', function open() {
  5.   const array = new Float32Array(5);

  6.   for (var i = 0; i < array.length; ++i) {
  7.     array[i] = i / 2;
  8.   }

  9.   ws.send(array);
  10. });
  11. ```

Simple server


  1. ``` js
  2. import { WebSocketServer } from 'ws';

  3. const wss = new WebSocketServer({ port: 8080 });

  4. wss.on('connection', function connection(ws) {
  5.   ws.on('message', function message(data) {
  6.     console.log('received: %s', data);
  7.   });

  8.   ws.send('something');
  9. });
  10. ```

External HTTP/S server


  1. ``` js
  2. import { createServer } from 'https';
  3. import { readFileSync } from 'fs';
  4. import { WebSocketServer } from 'ws';

  5. const server = createServer({
  6.   cert: readFileSync('/path/to/cert.pem'),
  7.   key: readFileSync('/path/to/key.pem')
  8. });
  9. const wss = new WebSocketServer({ server });

  10. wss.on('connection', function connection(ws) {
  11.   ws.on('message', function message(data) {
  12.     console.log('received: %s', data);
  13.   });

  14.   ws.send('something');
  15. });

  16. server.listen(8080);
  17. ```

Multiple servers sharing a single HTTP/S server


  1. ``` js
  2. import { createServer } from 'http';
  3. import { parse } from 'url';
  4. import { WebSocketServer } from 'ws';

  5. const server = createServer();
  6. const wss1 = new WebSocketServer({ noServer: true });
  7. const wss2 = new WebSocketServer({ noServer: true });

  8. wss1.on('connection', function connection(ws) {
  9.   // ...
  10. });

  11. wss2.on('connection', function connection(ws) {
  12.   // ...
  13. });

  14. server.on('upgrade', function upgrade(request, socket, head) {
  15.   const { pathname } = parse(request.url);

  16.   if (pathname === '/foo') {
  17.     wss1.handleUpgrade(request, socket, head, function done(ws) {
  18.       wss1.emit('connection', ws, request);
  19.     });
  20.   } else if (pathname === '/bar') {
  21.     wss2.handleUpgrade(request, socket, head, function done(ws) {
  22.       wss2.emit('connection', ws, request);
  23.     });
  24.   } else {
  25.     socket.destroy();
  26.   }
  27. });

  28. server.listen(8080);
  29. ```

Client authentication


  1. ``` js
  2. import { createServer } from 'http';
  3. import { WebSocketServer } from 'ws';

  4. const server = createServer();
  5. const wss = new WebSocketServer({ noServer: true });

  6. wss.on('connection', function connection(ws, request, client) {
  7.   ws.on('message', function message(data) {
  8.     console.log(`Received message ${data} from user ${client}`);
  9.   });
  10. });

  11. server.on('upgrade', function upgrade(request, socket, head) {
  12.   // This function is not defined on purpose. Implement it with your own logic.
  13.   authenticate(request, function next(err, client) {
  14.     if (err || !client) {
  15.       socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
  16.       socket.destroy();
  17.       return;
  18.     }

  19.     wss.handleUpgrade(request, socket, head, function done(ws) {
  20.       wss.emit('connection', ws, request, client);
  21.     });
  22.   });
  23. });

  24. server.listen(8080);
  25. ```

Also see the provided [example][session-parse-example] using express-session.

Server broadcast


A client WebSocket broadcasting to all connected WebSocket clients, including
itself.

  1. ``` js
  2. import WebSocket, { WebSocketServer } from 'ws';

  3. const wss = new WebSocketServer({ port: 8080 });

  4. wss.on('connection', function connection(ws) {
  5.   ws.on('message', function message(data, isBinary) {
  6.     wss.clients.forEach(function each(client) {
  7.       if (client.readyState === WebSocket.OPEN) {
  8.         client.send(data, { binary: isBinary });
  9.       }
  10.     });
  11.   });
  12. });
  13. ```

A client WebSocket broadcasting to every other connected WebSocket clients,
excluding itself.

  1. ``` js
  2. import WebSocket, { WebSocketServer } from 'ws';

  3. const wss = new WebSocketServer({ port: 8080 });

  4. wss.on('connection', function connection(ws) {
  5.   ws.on('message', function message(data, isBinary) {
  6.     wss.clients.forEach(function each(client) {
  7.       if (client !== ws && client.readyState === WebSocket.OPEN) {
  8.         client.send(data, { binary: isBinary });
  9.       }
  10.     });
  11.   });
  12. });
  13. ```

Round-trip time


  1. ``` js
  2. import WebSocket from 'ws';

  3. const ws = new WebSocket('wss://websocket-echo.com/');

  4. ws.on('open', function open() {
  5.   console.log('connected');
  6.   ws.send(Date.now());
  7. });

  8. ws.on('close', function close() {
  9.   console.log('disconnected');
  10. });

  11. ws.on('message', function message(data) {
  12.   console.log(`Round-trip time: ${Date.now() - data} ms`);

  13.   setTimeout(function timeout() {
  14.     ws.send(Date.now());
  15.   }, 500);
  16. });
  17. ```

Use the Node.js streams API


  1. ``` js
  2. import WebSocket, { createWebSocketStream } from 'ws';

  3. const ws = new WebSocket('wss://websocket-echo.com/');

  4. const duplex = createWebSocketStream(ws, { encoding: 'utf8' });

  5. duplex.pipe(process.stdout);
  6. process.stdin.pipe(duplex);
  7. ```

Other examples


For a full example with a browser client communicating with a ws server, see the
examples folder.

Otherwise, see the test cases.

FAQ


How to get the IP address of the client?


The remote IP address can be obtained from the raw socket.

  1. ``` js
  2. import { WebSocketServer } from 'ws';

  3. const wss = new WebSocketServer({ port: 8080 });

  4. wss.on('connection', function connection(ws, req) {
  5.   const ip = req.socket.remoteAddress;
  6. });
  7. ```

When the server runs behind a proxy like NGINX, the de-facto standard is to use
the X-Forwarded-For header.

  1. ``` js
  2. wss.on('connection', function connection(ws, req) {
  3.   const ip = req.headers['x-forwarded-for'].split(',')[0].trim();
  4. });
  5. ```

How to detect and close broken connections?


Sometimes the link between the server and the client can be interrupted in a way
that keeps both the server and the client unaware of the broken state of the
connection (e.g. when pulling the cord).

In these cases ping messages can be used as a means to verify that the remote
endpoint is still responsive.

  1. ``` js
  2. import { WebSocketServer } from 'ws';

  3. function heartbeat() {
  4.   this.isAlive = true;
  5. }

  6. const wss = new WebSocketServer({ port: 8080 });

  7. wss.on('connection', function connection(ws) {
  8.   ws.isAlive = true;
  9.   ws.on('pong', heartbeat);
  10. });

  11. const interval = setInterval(function ping() {
  12.   wss.clients.forEach(function each(ws) {
  13.     if (ws.isAlive === false) return ws.terminate();

  14.     ws.isAlive = false;
  15.     ws.ping();
  16.   });
  17. }, 30000);

  18. wss.on('close', function close() {
  19.   clearInterval(interval);
  20. });
  21. ```

Pong messages are automatically sent in response to ping messages as required by
the spec.

Just like the server example above your clients might as well lose connection
without knowing it. You might want to add a ping listener on your clients to
prevent that. A simple implementation would be:

  1. ``` js
  2. import WebSocket from 'ws';

  3. function heartbeat() {
  4.   clearTimeout(this.pingTimeout);

  5.   // Use `WebSocket#terminate()`, which immediately destroys the connection,
  6.   // instead of `WebSocket#close()`, which waits for the close timer.
  7.   // Delay should be equal to the interval at which your server
  8.   // sends out pings plus a conservative assumption of the latency.
  9.   this.pingTimeout = setTimeout(() => {
  10.     this.terminate();
  11.   }, 30000 + 1000);
  12. }

  13. const client = new WebSocket('wss://websocket-echo.com/');

  14. client.on('open', heartbeat);
  15. client.on('ping', heartbeat);
  16. client.on('close', function clear() {
  17.   clearTimeout(this.pingTimeout);
  18. });
  19. ```

How to connect via a proxy?


Use a custom http.Agent implementation like [https-proxy-agent][] or
[socks-proxy-agent][].

Changelog


We're using the GitHub [releases][changelog] for changelog entries.

License



[changelog]: https://github.com/websockets/ws/releases
[client-report]: http://websockets.github.io/ws/autobahn/clients/
[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
[node-zlib-bug]: https://github.com/nodejs/node/issues/8871
[node-zlib-deflaterawdocs]:
  https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options
[permessage-deflate]: https://tools.ietf.org/html/rfc7692
[server-report]: http://websockets.github.io/ws/autobahn/servers/
[session-parse-example]: ./examples/express-session-parse
[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback