1 # ws: a Node.js WebSocket library
3 [![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws)
4 [![Build](https://img.shields.io/github/workflow/status/websockets/ws/CI/master?label=build&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster)
5 [![Windows x86 Build](https://img.shields.io/appveyor/ci/lpinca/ws/master.svg?logo=appveyor)](https://ci.appveyor.com/project/lpinca/ws)
6 [![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/github/websockets/ws)
8 ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
11 Passes the quite extensive Autobahn test suite: [server][server-report],
12 [client][client-report].
14 **Note**: This module does not work in the browser. The client in the docs is a
15 reference to a back end with the role of a client in the WebSocket
16 communication. Browser clients must use the native
17 [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
18 object. To make the same code work seamlessly on Node.js and the browser, you
19 can use one of the many wrappers available on npm, like
20 [isomorphic-ws](https://github.com/heineiuo/isomorphic-ws).
24 - [Protocol support](#protocol-support)
25 - [Installing](#installing)
26 - [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance)
27 - [API docs](#api-docs)
28 - [WebSocket compression](#websocket-compression)
29 - [Usage examples](#usage-examples)
30 - [Sending and receiving text data](#sending-and-receiving-text-data)
31 - [Sending binary data](#sending-binary-data)
32 - [Simple server](#simple-server)
33 - [External HTTP/S server](#external-https-server)
34 - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server)
35 - [Client authentication](#client-authentication)
36 - [Server broadcast](#server-broadcast)
37 - [echo.websocket.org demo](#echowebsocketorg-demo)
38 - [Use the Node.js streams API](#use-the-nodejs-streams-api)
39 - [Other examples](#other-examples)
41 - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client)
42 - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections)
43 - [How to connect via a proxy?](#how-to-connect-via-a-proxy)
44 - [Changelog](#changelog)
49 - **HyBi drafts 07-12** (Use the option `protocolVersion: 8`)
50 - **HyBi drafts 13-17** (Current default, alternatively option
51 `protocolVersion: 13`)
59 ### Opt-in for performance and spec compliance
61 There are 2 optional modules that can be installed along side with the ws
62 module. These modules are binary addons which improve certain operations.
63 Prebuilt binaries are available for the most popular platforms so you don't
64 necessarily need to have a C++ compiler installed on your machine.
66 - `npm install --save-optional bufferutil`: Allows to efficiently perform
67 operations such as masking and unmasking the data payload of the WebSocket
69 - `npm install --save-optional utf-8-validate`: Allows to efficiently check if a
70 message contains valid UTF-8 as required by the spec.
74 See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and
77 ## WebSocket compression
79 ws supports the [permessage-deflate extension][permessage-deflate] which enables
80 the client and server to negotiate a compression algorithm and its parameters,
81 and then selectively apply it to the data payloads of each WebSocket message.
83 The extension is disabled by default on the server and enabled by default on the
84 client. It adds a significant overhead in terms of performance and memory
85 consumption so we suggest to enable it only if it is really needed.
87 Note that Node.js has a variety of issues with high-performance compression,
88 where increased concurrency, especially on Linux, can lead to [catastrophic
89 memory fragmentation][node-zlib-bug] and slow performance. If you intend to use
90 permessage-deflate in production, it is worthwhile to set up a test
91 representative of your workload and ensure Node.js/zlib will handle it with
92 acceptable performance and memory usage.
94 Tuning of permessage-deflate can be done via the options defined below. You can
95 also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly
96 into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs].
98 See [the docs][ws-server-options] for more options.
101 const WebSocket = require('ws');
103 const wss = new WebSocket.Server({
106 zlibDeflateOptions: {
107 // See zlib defaults.
112 zlibInflateOptions: {
115 // Other options settable:
116 clientNoContextTakeover: true, // Defaults to negotiated value.
117 serverNoContextTakeover: true, // Defaults to negotiated value.
118 serverMaxWindowBits: 10, // Defaults to negotiated value.
119 // Below options specified as default values.
120 concurrencyLimit: 10, // Limits zlib concurrency for perf.
121 threshold: 1024 // Size (in bytes) below which messages
122 // should not be compressed.
127 The client will only use the extension if it is supported and enabled on the
128 server. To always disable the extension on the client set the
129 `perMessageDeflate` option to `false`.
132 const WebSocket = require('ws');
134 const ws = new WebSocket('ws://www.host.com/path', {
135 perMessageDeflate: false
141 ### Sending and receiving text data
144 const WebSocket = require('ws');
146 const ws = new WebSocket('ws://www.host.com/path');
148 ws.on('open', function open() {
149 ws.send('something');
152 ws.on('message', function incoming(data) {
157 ### Sending binary data
160 const WebSocket = require('ws');
162 const ws = new WebSocket('ws://www.host.com/path');
164 ws.on('open', function open() {
165 const array = new Float32Array(5);
167 for (var i = 0; i < array.length; ++i) {
178 const WebSocket = require('ws');
180 const wss = new WebSocket.Server({ port: 8080 });
182 wss.on('connection', function connection(ws) {
183 ws.on('message', function incoming(message) {
184 console.log('received: %s', message);
187 ws.send('something');
191 ### External HTTP/S server
194 const fs = require('fs');
195 const https = require('https');
196 const WebSocket = require('ws');
198 const server = https.createServer({
199 cert: fs.readFileSync('/path/to/cert.pem'),
200 key: fs.readFileSync('/path/to/key.pem')
202 const wss = new WebSocket.Server({ server });
204 wss.on('connection', function connection(ws) {
205 ws.on('message', function incoming(message) {
206 console.log('received: %s', message);
209 ws.send('something');
215 ### Multiple servers sharing a single HTTP/S server
218 const http = require('http');
219 const WebSocket = require('ws');
220 const url = require('url');
222 const server = http.createServer();
223 const wss1 = new WebSocket.Server({ noServer: true });
224 const wss2 = new WebSocket.Server({ noServer: true });
226 wss1.on('connection', function connection(ws) {
230 wss2.on('connection', function connection(ws) {
234 server.on('upgrade', function upgrade(request, socket, head) {
235 const pathname = url.parse(request.url).pathname;
237 if (pathname === '/foo') {
238 wss1.handleUpgrade(request, socket, head, function done(ws) {
239 wss1.emit('connection', ws, request);
241 } else if (pathname === '/bar') {
242 wss2.handleUpgrade(request, socket, head, function done(ws) {
243 wss2.emit('connection', ws, request);
253 ### Client authentication
256 const http = require('http');
257 const WebSocket = require('ws');
259 const server = http.createServer();
260 const wss = new WebSocket.Server({ noServer: true });
262 wss.on('connection', function connection(ws, request, client) {
263 ws.on('message', function message(msg) {
264 console.log(`Received message ${msg} from user ${client}`);
268 server.on('upgrade', function upgrade(request, socket, head) {
269 // This function is not defined on purpose. Implement it with your own logic.
270 authenticate(request, (err, client) => {
271 if (err || !client) {
272 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
277 wss.handleUpgrade(request, socket, head, function done(ws) {
278 wss.emit('connection', ws, request, client);
286 Also see the provided [example][session-parse-example] using `express-session`.
290 A client WebSocket broadcasting to all connected WebSocket clients, including
294 const WebSocket = require('ws');
296 const wss = new WebSocket.Server({ port: 8080 });
298 wss.on('connection', function connection(ws) {
299 ws.on('message', function incoming(data) {
300 wss.clients.forEach(function each(client) {
301 if (client.readyState === WebSocket.OPEN) {
309 A client WebSocket broadcasting to every other connected WebSocket clients,
313 const WebSocket = require('ws');
315 const wss = new WebSocket.Server({ port: 8080 });
317 wss.on('connection', function connection(ws) {
318 ws.on('message', function incoming(data) {
319 wss.clients.forEach(function each(client) {
320 if (client !== ws && client.readyState === WebSocket.OPEN) {
328 ### echo.websocket.org demo
331 const WebSocket = require('ws');
333 const ws = new WebSocket('wss://echo.websocket.org/', {
334 origin: 'https://websocket.org'
337 ws.on('open', function open() {
338 console.log('connected');
342 ws.on('close', function close() {
343 console.log('disconnected');
346 ws.on('message', function incoming(data) {
347 console.log(`Roundtrip time: ${Date.now() - data} ms`);
349 setTimeout(function timeout() {
355 ### Use the Node.js streams API
358 const WebSocket = require('ws');
360 const ws = new WebSocket('wss://echo.websocket.org/', {
361 origin: 'https://websocket.org'
364 const duplex = WebSocket.createWebSocketStream(ws, { encoding: 'utf8' });
366 duplex.pipe(process.stdout);
367 process.stdin.pipe(duplex);
372 For a full example with a browser client communicating with a ws server, see the
375 Otherwise, see the test cases.
379 ### How to get the IP address of the client?
381 The remote IP address can be obtained from the raw socket.
384 const WebSocket = require('ws');
386 const wss = new WebSocket.Server({ port: 8080 });
388 wss.on('connection', function connection(ws, req) {
389 const ip = req.socket.remoteAddress;
393 When the server runs behind a proxy like NGINX, the de-facto standard is to use
394 the `X-Forwarded-For` header.
397 wss.on('connection', function connection(ws, req) {
398 const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
402 ### How to detect and close broken connections?
404 Sometimes the link between the server and the client can be interrupted in a way
405 that keeps both the server and the client unaware of the broken state of the
406 connection (e.g. when pulling the cord).
408 In these cases ping messages can be used as a means to verify that the remote
409 endpoint is still responsive.
412 const WebSocket = require('ws');
416 function heartbeat() {
420 const wss = new WebSocket.Server({ port: 8080 });
422 wss.on('connection', function connection(ws) {
424 ws.on('pong', heartbeat);
427 const interval = setInterval(function ping() {
428 wss.clients.forEach(function each(ws) {
429 if (ws.isAlive === false) return ws.terminate();
436 wss.on('close', function close() {
437 clearInterval(interval);
441 Pong messages are automatically sent in response to ping messages as required by
444 Just like the server example above your clients might as well lose connection
445 without knowing it. You might want to add a ping listener on your clients to
446 prevent that. A simple implementation would be:
449 const WebSocket = require('ws');
451 function heartbeat() {
452 clearTimeout(this.pingTimeout);
454 // Use `WebSocket#terminate()`, which immediately destroys the connection,
455 // instead of `WebSocket#close()`, which waits for the close timer.
456 // Delay should be equal to the interval at which your server
457 // sends out pings plus a conservative assumption of the latency.
458 this.pingTimeout = setTimeout(() => {
463 const client = new WebSocket('wss://echo.websocket.org/');
465 client.on('open', heartbeat);
466 client.on('ping', heartbeat);
467 client.on('close', function clear() {
468 clearTimeout(this.pingTimeout);
472 ### How to connect via a proxy?
474 Use a custom `http.Agent` implementation like [https-proxy-agent][] or
475 [socks-proxy-agent][].
479 We're using the GitHub [releases][changelog] for changelog entries.
485 [changelog]: https://github.com/websockets/ws/releases
486 [client-report]: http://websockets.github.io/ws/autobahn/clients/
487 [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
488 [node-zlib-bug]: https://github.com/nodejs/node/issues/8871
489 [node-zlib-deflaterawdocs]:
490 https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options
491 [permessage-deflate]: https://tools.ietf.org/html/rfc7692
492 [server-report]: http://websockets.github.io/ws/autobahn/servers/
493 [session-parse-example]: ./examples/express-session-parse
494 [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
496 https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback