Technical Documentation: websockets/ws
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (`README.md`)
ws: a Node.js WebSocket library
ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
server implementation.
Passes the quite extensive Autobahn test suite: server,
client.
Note: This module does not work in the browser. The client in the docs is a
reference to a backend with the role of a client in the WebSocket communication.
Browser clients must use the nativeWebSocket
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
isomorphic-ws.
Table of Contents
Protocol support
- HyBi drafts 07-12 (Use the option
protocolVersion: 8) - HyBi drafts 13-17 (Current default, alternatively option
protocolVersion: 13)
Installing
npm install wsOpt-in for performance
bufferutil is an optional module that can be installed alongside the ws
module:
npm install --save-optional bufferutilThis is a binary addon that improves the performance of certain operations such
as masking and unmasking the data payload of the WebSocket frames. Prebuilt
binaries are available for the most popular platforms, so you don't necessarily
need to have a C++ compiler installed on your machine.
To force ws to not use bufferutil, use theWS_NO_BUFFER_UTIL environment variable. This
can 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.
Legacy opt-in for performance
If you are running on an old version of Node.js (prior to v18.14.0), ws also
supports the utf-8-validate module:
npm install --save-optional utf-8-validateThis contains a binary polyfill for buffer.isUtf8().
To force ws not to use utf-8-validate, use theWS_NO_UTF_8_VALIDATE environment variable.
API docs
See /doc/ws.md for Node.js-like documentation of ws classes and
utility functions.
WebSocket compression
ws supports the permessage-deflate extension 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 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.
See the docs for more options.
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({
port: 8080,
perMessageDeflate: {
zlibDeflateOptions: {
// See zlib defaults.
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below which messages
// should not be compressed if context takeover is disabled.
}
});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 theperMessageDeflate option to false.
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path', {
perMessageDeflate: false
});Usage examples
Sending and receiving text data
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});Sending binary data
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
ws.on('open', function open() {
const array = new Float32Array(5);
for (var i = 0; i < array.length; ++i) {
array[i] = i / 2;
}
ws.send(array);
});Simple server
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});External HTTP/S server
import { createServer } from 'https';
import { readFileSync } from 'fs';
import { WebSocketServer } from 'ws';
const server = createServer({
cert: readFileSync('/path/to/cert.pem'),
key: readFileSync('/path/to/key.pem')
});
const wss = new WebSocketServer({ server });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
server.listen(8080);Multiple servers sharing a single HTTP/S server
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
const server = createServer();
const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });
wss1.on('connection', function connection(ws) {
ws.on('error', console.error);
// ...
});
wss2.on('connection', function connection(ws) {
ws.on('error', console.error);
// ...
});
server.on('upgrade', function upgrade(request, socket, head) {
const { pathname } = new URL(request.url, 'wss://base.url');
if (pathname === '/foo') {
wss1.handleUpgrade(request, socket, head, function done(ws) {
wss1.emit('connection', ws, request);
});
} else if (pathname === '/bar') {
wss2.handleUpgrade(request, socket, head, function done(ws) {
wss2.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
server.listen(8080);Client authentication
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
function onSocketError(err) {
console.error(err);
}
const server = createServer();
const wss = new WebSocketServer({ noServer: true });
wss.on('connection', function connection(ws, request, client) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log(`Received message ${data} from user ${client}`);
});
});
server.on('upgrade', function upgrade(request, socket, head) {
socket.on('error', onSocketError);
// This function is not defined on purpose. Implement it with your own logic.
authenticate(request, function next(err, client) {
if (err || !client) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
socket.removeListener('error', onSocketError);
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request, client);
});
});
});
server.listen(8080);Also see the provided example using express-session.
Server broadcast
A client WebSocket broadcasting to all connected WebSocket clients, including
itself.
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data, isBinary) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
});
});
});A client WebSocket broadcasting to every other connected WebSocket clients,
excluding itself.
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data, isBinary) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
});
});
});Round-trip time
import WebSocket from 'ws';
const ws = new WebSocket('wss://websocket-echo.com/');
ws.on('error', console.error);
ws.on('open', function open() {
console.log('connected');
ws.send(Date.now());
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function message(data) {
console.log(`Round-trip time: ${Date.now() - data} ms`);
setTimeout(function timeout() {
ws.send(Date.now());
}, 500);
});Use the Node.js streams API
import WebSocket, { createWebSocketStream } from 'ws';
const ws = new WebSocket('wss://websocket-echo.com/');
const duplex = createWebSocketStream(ws, { encoding: 'utf8' });
duplex.on('error', console.error);
duplex.pipe(process.stdout);
process.stdin.pipe(duplex);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.
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws, req) {
const ip = req.socket.remoteAddress;
ws.on('error', console.error);
});When the server runs behind a proxy like NGINX, the de-facto standard is to use
the X-Forwarded-For header.
wss.on('connection', function connection(ws, req) {
const ip = req.headers['x-forwarded-for'].split(',')[0].trim();
ws.on('error', console.error);
});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.
import { WebSocketServer } from 'ws';
function heartbeat() {
this.isAlive = true;
}
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.isAlive = true;
ws.on('error', console.error);
ws.on('pong', heartbeat);
});
const interval = setInterval(function ping() {
wss.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);
wss.on('close', function close() {
clearInterval(interval);
});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:
import WebSocket from 'ws';
function heartbeat() {
clearTimeout(this.pingTimeout);
// Use `WebSocket#terminate()`, which immediately destroys the connection,
// instead of `WebSocket#close()`, which waits for the close timer.
// Delay should be equal to the interval at which your server
// sends out pings plus a conservative assumption of the latency.
this.pingTimeout = setTimeout(() => {
this.terminate();
}, 30000 + 1000);
}
const client = new WebSocket('wss://websocket-echo.com/');
client.on('error', console.error);
client.on('open', heartbeat);
client.on('ping', heartbeat);
client.on('close', function clear() {
clearTimeout(this.pingTimeout);
});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 for changelog entries.
License
Doc Ws (`doc/ws.md`)
ws
Table of Contents
- Class: WebSocketServer
- Class: WebSocket
- Ready state constants
- new WebSocket(address[, protocols][, options])
- Event: 'close'
- Event: 'error'
- Event: 'message'
- Event: 'open'
- Event: 'ping'
- Event: 'pong'
- Event: 'redirect'
- Event: 'unexpected-response'
- Event: 'upgrade'
- websocket.addEventListener(type, listener[, options])
- websocket.binaryType
- websocket.bufferedAmount
- [websocket.close([code[, reason]])](#websocketclosecode-reason)
- websocket.extensions
- websocket.isPaused
- websocket.onclose
- websocket.onerror
- websocket.onmessage
- websocket.onopen
- websocket.pause()
- [websocket.ping([data[, mask]][, callback])](#websocketpingdata-mask-callback)
- [websocket.pong([data[, mask]][, callback])](#websocketpongdata-mask-callback)
- websocket.protocol
- websocket.readyState
- websocket.removeEventListener(type, listener)
- websocket.resume()
- websocket.send(data[, options][, callback])
- websocket.terminate()
- websocket.url
- createWebSocketStream(websocket[, options])
- Environment variables
- Error codes
- WS_ERR_EXPECTED_FIN
- WS_ERR_EXPECTED_MASK
- WS_ERR_INVALID_CLOSE_CODE
- WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH
- WS_ERR_INVALID_OPCODE
- WS_ERR_INVALID_UTF8
- WS_ERR_UNEXPECTED_MASK
- WS_ERR_UNEXPECTED_RSV_1
- WS_ERR_UNEXPECTED_RSV_2_3
- WS_ERR_TOO_MANY_BUFFERED_PARTS
- WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH
- WS_ERR_UNSUPPORTED_MESSAGE_LENGTH
Class: WebSocketServer
This class represents a WebSocket server. It extends the EventEmitter.
new WebSocketServer(options[, callback])
options{Object}allowSynchronousEvents{Boolean} Specifies whether any of the'message','ping', and'pong'events can be emitted multiple times in the same
tick. Defaults totrue. Setting it tofalseimproves compatibility with
the WHATWG standard but may negatively impact performance.autoPong{Boolean} Specifies whether or not to automatically send a pong
in response to a ping. Defaults totrue.backlog{Number} The maximum length of the queue of pending connections.clientTracking{Boolean} Specifies whether or not to track clients.closeTimeout{Number} Duration in milliseconds to wait for a graceful
close afterwebsocket.close()is called. If the limit is reached, the
connection is forcibly terminated. Defaults to 30000.handleProtocols{Function} A function which can be used to handle the
WebSocket subprotocols. See description below.host{String} The hostname where to bind the server.maxBufferedChunks{Number} The maximum number of buffered data chunks. The
value is coerced to a 32-bit signed integer. Defaults to 262144. Set to 0 to
disable the limit.maxFragments{Number} The maximum number of fragments in a message. The
value is coerced to a 32-bit signed integer. Defaults to 16384. Set to 0 to
disable the limit.maxPayload{Number} The maximum allowed message size in bytes. The value
is coerced to a 32-bit signed integer. Defaults to 104857600 (100 MiB). Set
to 0 to disable the limit.noServer{Boolean} Enable no server mode.path{String} Accept only connections matching this path.perMessageDeflate{Boolean|Object} Enable/disable permessage-deflate.port{Number} The port where to bind the server.server{http.Server|https.Server} A pre-created Node.js HTTP/S server.skipUTF8Validation{Boolean} Specifies whether or not to skip UTF-8
validation for text and close messages. Defaults tofalse. Set totrue
only if clients are trusted.verifyClient{Function} A function which can be used to validate incoming
connections. See description below. (Usage is discouraged: see
Issue #337)WebSocket{Function} Specifies theWebSocketclass to be used. It must
be extended from the originalWebSocket. Defaults toWebSocket.
callback{Function}
Create a new server instance. One and only one of port, server or noServer
must be provided or an error is thrown. An HTTP server is automatically created,
started, and used if port is set. To use an external HTTP/S server instead,
specify only server or noServer. In this case, the HTTP/S server must be
started manually. The "noServer" mode allows the WebSocket server to be
completely detached from the HTTP/S server. This makes it possible, for example,
to share a single HTTP/S server between multiple WebSocket servers.
NOTE: Use of
verifyClientis discouraged. Rather handle client
authentication in the'upgrade'event of the HTTP server. See examples for
more details.
If verifyClient is not set, then the handshake is automatically accepted. If
it has a single parameter, then ws will invoke it with the following argument:
info{Object}origin{String} The value in the Origin header indicated by the client.req{http.IncomingMessage} The client HTTP GET request.secure{Boolean}trueifreq.socket.authorizedorreq.socket.encryptedis set.
The return value (Boolean) of the function determines whether or not to accept
the handshake.
If verifyClient has two parameters, then ws will invoke it with the
following arguments:
info{Object} Same as above.cb{Function} A callback that must be called by the user upon inspection of
theinfofields. Arguments in this callback are:result{Boolean} Whether or not to accept the handshake.code{Number} Whenresultisfalse, this field determines the HTTP
error status code to be sent to the client.name{String} Whenresultisfalse, this field determines the HTTP
reason phrase.headers{Object} Whenresultisfalse, this field determines
additional HTTP headers to be sent to the client. For example,{ 'Retry-After': 120 }.
handleProtocols takes two arguments:
protocols{Set} The list of WebSocket subprotocols indicated by the client
in theSec-WebSocket-Protocolheader.request{http.IncomingMessage} The client HTTP GET request.
The returned value sets the value of the Sec-WebSocket-Protocol header in the
HTTP 101 response. If returned value is false, the header is not added in the
response.
If handleProtocols is not set, then the first of the client's requested
subprotocols is used.
perMessageDeflate can be used to control the behavior of permessage-deflate
extension. The extension is disabled when false (default
value). If an object is provided, then that is extension parameters:
serverNoContextTakeover{Boolean} Whether to use context takeover or not.clientNoContextTakeover{Boolean} Acknowledge disabling of client context
takeover.serverMaxWindowBits{Number} The value ofwindowBits.clientMaxWindowBits{Number} Request a custom client window size.zlibDeflateOptions{Object} Additional options to pass to
zlib on deflate.zlibInflateOptions{Object} Additional options to pass to
zlib on inflate.threshold{Number} Payloads smaller than this will not be compressed if
context takeover is disabled. Defaults to 1024 bytes.concurrencyLimit{Number} The number of concurrent calls to zlib. Calls
above this limit will be queued. Default 10. You usually won't need to touch
this option. See this issue for more details.
If a property is empty, then either an offered configuration or a default value
is used. When sending a fragmented message, the length of the first fragment is
compared to the threshold. This determines if compression is used for the entire
message.
callback will be added as a listener for the 'listening' event on the HTTP
server when the port option is set.
Event: 'close'
Emitted when the server closes. This event depends on the 'close' event of
HTTP server only when it is created internally. In all other cases, the event is
emitted independently.
Event: 'connection'
websocket{WebSocket}request{http.IncomingMessage}
Emitted when the handshake is complete. request is the http GET request sent
by the client. Useful for parsing authority headers, cookie headers, and other
information.
Event: 'error'
error{Error}
Emitted when an error occurs on the underlying server.
Event: 'headers'
headers{Array}request{http.IncomingMessage}
Emitted before the response headers are written to the socket as part of the
handshake. This allows you to inspect/modify the headers before they are sent.
Event: 'listening'
Emitted when the underlying server has been bound.
Event: 'wsClientError'
error{Error}socket{net.Socket|tls.Socket}request{http.IncomingMessage}
Emitted when an error occurs before the WebSocket connection is established.socket and request are respectively the socket and the HTTP request from
which the error originated. The listener of this event is responsible for
closing the socket. When the 'wsClientError' event is emitted there is nohttp.ServerResponse object, so any HTTP response, including the response
headers and body, must be written directly to the socket. If there is no
listener for this event, the socket is closed with a default 4xx response
containing a descriptive error message.
server.address()
Returns an object with port, family, and address properties specifying the
bound address, the address family name, and port of the server as reported by
the operating system if listening on an IP socket. If the server is listening on
a pipe or UNIX domain socket, the name is returned as a string.
server.clients
- {Set}
A set that stores all connected clients. This property is only added when theclientTracking is truthy.
server.close([callback])
Prevent the server from accepting new connections and close the HTTP server if
created internally. If an external HTTP server is used via the server ornoServer constructor options, it must be closed manually. Existing connections
are not closed automatically. The server emits a 'close' event when all
connections are closed unless an external HTTP server is used and client
tracking is disabled. In this case, the 'close' event is emitted in the next
tick. The optional callback is called when the 'close' event occurs and
receives an Error if the server is already closed.
server.handleUpgrade(request, socket, head, callback)
request{http.IncomingMessage} The client HTTP GET request.socket{stream.Duplex} The network socket between the server and client.head{Buffer} The first packet of the upgraded stream.callback{Function}
Handle a HTTP upgrade request. When the HTTP server is created internally or
when the HTTP server is passed via the server option, this method is called
automatically. When operating in "noServer" mode, this method must be called
manually.
If the upgrade is successful, the callback is called with two arguments:
websocket{WebSocket} AWebSocketobject.request{http.IncomingMessage} The client HTTP GET request.
server.shouldHandle(request)
request{http.IncomingMessage} The client HTTP GET request.
See if a given request should be handled by this server. By default, this method
validates the pathname of the request, matching it against the path option if
provided. The return value, true or false, determines whether or not to
accept the handshake.
This method can be overridden when a custom handling logic is required.
Class: WebSocket
This class represents a WebSocket. It extends the EventEmitter.
Ready state constants
| Constant | Value | Description |
|---|---|---|
| CONNECTING | 0 | The connection is not yet open. |
| OPEN | 1 | The connection is open and ready to communicate. |
| CLOSING | 2 | The connection is in the process of closing. |
| CLOSED | 3 | The connection is closed. |
new WebSocket(address[, protocols][, options])
address{String|url.URL} The URL to which to connect.protocols{String|Array} The list of subprotocols. If specified, this
overrides theprotocolsoption.options{Object}allowSynchronousEvents{Boolean} Specifies whether any of the'message','ping', and'pong'events can be emitted multiple times in the same
tick. Defaults totrue. Setting it tofalseimproves compatibility with
the WHATWG standard but may negatively impact performance.autoPong{Boolean} Specifies whether or not to automatically send a pong
in response to a ping. Defaults totrue.closeTimeout{Number} Duration in milliseconds to wait for a graceful
close afterwebsocket.close()is called. If the limit is reached, the
connection is forcibly terminated. Defaults to 30000.finishRequest{Function} A function which can be used to customize the
headers of each HTTP request before it is sent. See description below.followRedirects{Boolean} Whether or not to follow redirects. Defaults tofalse.generateMask{Function} The function used to generate the masking key. It
takes aBufferthat must be filled synchronously and is called before a
message is sent, for each message. By default, the buffer is filled with
cryptographically strong random bytes.handshakeTimeout{Number} Timeout in milliseconds for the handshake
request. This is reset after every redirection.maxBufferedChunks{Number} The maximum number of buffered data chunks. The
value is coerced to a 32-bit signed integer. Defaults to 262144. Set to 0 to
disable the limit.maxFragments{Number} The maximum number of fragments in a message. The
value is coerced to a 32-bit signed integer. Defaults to 16384. Set to 0 to
disable the limit.maxPayload{Number} The maximum allowed message size in bytes. The value
is coerced to a 32-bit signed integer. Defaults to 104857600 (100 MiB). Set
to 0 to disable the limit.maxRedirects{Number} The maximum number of redirects allowed. Defaults
to 10.origin{String} Value of theOriginorSec-WebSocket-Originheader
depending on theprotocolVersion.perMessageDeflate{Boolean|Object} Enable/disable permessage-deflate.protocols{String|Array} The list of subprotocols.protocolVersion{Number} Value of theSec-WebSocket-Versionheader.skipUTF8Validation{Boolean} Specifies whether or not to skip UTF-8
validation for text and close messages. Defaults tofalse. Set totrue
only if the server is trusted.- Any other option allowed in
http.request()orhttps.request().
Options given do not have any effect if parsed from the URL given with theaddressparameter.
Create a new WebSocket instance.
perMessageDeflate default value is true. When using an object, parameters
are the same of the server. The only difference is the direction of requests.
For example, serverNoContextTakeover can be used to ask the server to disable
context takeover.
finishRequest is called with arguments
request{http.ClientRequest}websocket{WebSocket}
for each HTTP GET request (the initial one and any caused by redirects) when it
is ready to be sent, to allow for last minute customization of the headers. IffinishRequest is set, then it has the responsibility to call request.end()
once it is done setting request headers. This is intended for niche use-cases
where some headers can't be provided in advance e.g. because they depend on the
underlying socket.
IPC connections
ws supports IPC connections. To connect to an IPC endpoint, use the following
URL form:
On Unices
textws+unix:/absolute/path/to/uds_socket:/pathname?search_paramsOn Windows
textws+unix:\\.\pipe\pipe_name:/pathname?search_params
The character : is the separator between the IPC path (the UNIX domain socket
path or the Windows named pipe) and the URL path. The IPC path must not include
the characters : and ?, otherwise the URL is incorrectly parsed. If the URL
path is omitted
ws+unix:/absolute/path/to/uds_socketit defaults to /.
Event: 'close'
code{Number}reason{Buffer}
Emitted when the connection is closed. code is a numeric value indicating the
status code explaining why the connection has been closed. reason is aBuffer containing a human-readable string explaining why the connection has
been closed.
Event: 'error'
error{Error}
Emitted when an error occurs. Errors may have a .code property, matching one
of the string values defined below under Error codes.
Event: 'message'
data{ArrayBuffer|Blob|Buffer|Buffer[]}isBinary{Boolean}
Emitted when a message is received. data is the message content. isBinary
specifies whether the message is binary or not.
Event: 'open'
Emitted when the connection is established.
Event: 'ping'
data{Buffer}
Emitted when a ping is received.
Event: 'pong'
data{Buffer}
Emitted when a pong is received.
Event: 'redirect'
url{String}request{http.ClientRequest}
Emitted before a redirect is followed. url is the redirect URL. request is
the HTTP GET request with the headers queued. This event gives the ability to
inspect confidential headers and remove them on a per-redirect basis using therequest.getHeader() and request.removeHeader() API. The request
object should be used only for this purpose. When there is at least one listener
for this event, no header is removed by default, even if the redirect is to a
different domain.
Event: 'unexpected-response'
request{http.ClientRequest}response{http.IncomingMessage}
Emitted when the server response is not the expected one, for example a 401
response. This event gives the ability to read the response in order to extract
useful information. If the server sends an invalid response and there isn't a
listener for this event, an error is emitted.
Event: 'upgrade'
response{http.IncomingMessage}
Emitted when response headers are received from the server as part of the
handshake. This allows you to read headers from the server, for example
'set-cookie' headers.
websocket.addEventListener(type, listener[, options])
type{String} A string representing the event type to listen for.listener{Function|Object} The listener to add.options{Object}once{Boolean} ABooleanindicating that the listener should be invoked
at most once after being added. Iftrue, the listener would be
automatically removed when invoked.
Register an event listener emulating the EventTarget interface. This method
does nothing if type is not one of 'close', 'error', 'message', or'open'.
websocket.binaryType
- {String}
A string indicating the type of binary data being transmitted by the connection.
This should be one of "nodebuffer", "arraybuffer", "blob", or "fragments".
Defaults to "nodebuffer". Type "fragments" will emit the array of fragments as
received from the sender, without copyfull concatenation, which is useful for
the performance of binary protocols transferring large messages with multiple
fragments.
websocket.bufferedAmount
- {Number}
The number of bytes of data that have been queued using calls to send() but
not yet transmitted to the network. This deviates from the HTML standard in the
following ways:
- If the data is immediately sent, the value is
0. - All framing bytes are included.
websocket.close([code[, reason]])
code{Number} A numeric value indicating the status code explaining why the
connection is being closed.reason{String|Buffer} The reason why the connection is closing.
Initiate a closing handshake.
websocket.isPaused
- {Boolean}
Indicates whether the websocket is paused.
websocket.extensions
- {Object}
An object containing the negotiated extensions.
websocket.onclose
- {Function}
An event listener to be called when connection is closed. The listener receives
a CloseEvent named "close".
websocket.onerror
- {Function}
An event listener to be called when an error occurs. The listener receives anErrorEvent named "error".
websocket.onmessage
- {Function}
An event listener to be called when a message is received. The listener receives
a MessageEvent named "message".
websocket.onopen
- {Function}
An event listener to be called when the connection is established. The listener
receives an OpenEvent named "open".
websocket.pause()
Pause the websocket causing it to stop emitting events. Some events can still be
emitted after this is called, until all buffered data is consumed. This method
is a noop if the ready state is CONNECTING or CLOSED.
websocket.ping([data[, mask]][, callback])
data
{Array|Number|Object|String|ArrayBuffer|Buffer|DataView|TypedArray|Blob} The
data to send in the ping frame.mask{Boolean} Specifies whetherdatashould be masked or not. Defaults totruewhenwebsocketis not a server client.callback{Function} An optional callback which is invoked when the ping
frame is written out. If an error occurs, the callback is called with the
error as its first argument.
Send a ping. This method throws an error if the ready state is CONNECTING.
websocket.pong([data[, mask]][, callback])
data
{Array|Number|Object|String|ArrayBuffer|Buffer|DataView|TypedArray|Blob} The
data to send in the pong frame.mask{Boolean} Specifies whetherdatashould be masked or not. Defaults totruewhenwebsocketis not a server client.callback{Function} An optional callback which is invoked when the pong
frame is written out. If an error occurs, the callback is called with the
error as its first argument.
Send a pong. This method throws an error if the ready state is CONNECTING.
websocket.protocol
- {String}
The subprotocol selected by the server.
websocket.resume()
Make a paused socket resume emitting events. This method is a noop if the ready
state is CONNECTING or CLOSED.
websocket.readyState
- {Number}
The current state of the connection. This is one of the ready state constants.
websocket.removeEventListener(type, listener)
type{String} A string representing the event type to remove.listener{Function|Object} The listener to remove.
Removes an event listener emulating the EventTarget interface. This method
only removes listeners added withwebsocket.addEventListener().
websocket.send(data[, options][, callback])
data
{Array|Number|Object|String|ArrayBuffer|Buffer|DataView|TypedArray|Blob} The
data to send.Objectvalues are only supported if they conform to the
requirements ofBuffer.from(). If those constraints are not met, aTypeErroris thrown.options{Object}binary{Boolean} Specifies whetherdatashould be sent as a binary or
not. Default is autodetected.compress{Boolean} Specifies whetherdatashould be compressed or not.
Defaults totruewhen permessage-deflate is enabled.fin{Boolean} Specifies whetherdatais the last fragment of a message
or not. Defaults totrue.mask{Boolean} Specifies whetherdatashould be masked or not. Defaults
totruewhenwebsocketis not a server client.
callback{Function} An optional callback which is invoked whendatais
written out. If an error occurs, the callback is called with the error as its
first argument.
Send data through the connection. This method throws an error if the ready
state is CONNECTING.
websocket.terminate()
Forcibly close the connection. Internally, this calls socket.destroy().
websocket.url
- {String}
The URL of the WebSocket server. Server clients don't have this attribute.
createWebSocketStream(websocket[, options])
websocket{WebSocket} AWebSocketobject.options{Object} Options to pass to theDuplex
constructor.
Returns a Duplex stream that allows to use the Node.js streams API on top of a
given WebSocket.
Environment variables
WS_NO_BUFFER_UTIL
When set to a non-empty value, prevents the optional bufferutil dependency
from being required.
WS_NO_UTF_8_VALIDATE
When set to a non-empty value, prevents the optional utf-8-validate dependency
from being required.
Error codes
Errors emitted by the websocket may have a .code property, describing the
specific type of error that has occurred:
WS_ERR_EXPECTED_FIN
A WebSocket frame was received with the FIN bit not set when it was expected.
WS_ERR_EXPECTED_MASK
An unmasked WebSocket frame was received by a WebSocket server.
WS_ERR_INVALID_CLOSE_CODE
A WebSocket close frame was received with an invalid close code.
WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH
A control frame with an invalid payload length was received.
WS_ERR_INVALID_OPCODE
A WebSocket frame was received with an invalid opcode.
WS_ERR_INVALID_UTF8
A text or close frame was received containing invalid UTF-8 data.
WS_ERR_UNEXPECTED_MASK
A masked WebSocket frame was received by a WebSocket client.
WS_ERR_UNEXPECTED_RSV_1
A WebSocket frame was received with the RSV1 bit set unexpectedly.
WS_ERR_UNEXPECTED_RSV_2_3
A WebSocket frame was received with the RSV2 or RSV3 bit set unexpectedly.
WS_ERR_TOO_MANY_BUFFERED_PARTS
The configured maximum number of buffered data chunks or message fragments was
exceeded.
WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH
A data frame was received with a length longer than the max supported length
(2^53 - 1, due to JavaScript language limitations).
WS_ERR_UNSUPPORTED_MESSAGE_LENGTH
A message was received with a length longer than the maximum supported length,
as configured by the maxPayload option.
--- METRICS ---
- Files Extracted: 2
- Estimated Token Budget: ~11107 tokens
- Canonical Reference: https://codewiki.google/github.com/websockets/ws