### Install ws Package Source: https://github.com/websockets/ws/blob/master/README.md Install the ws package using npm. This is the primary step to begin using the library. ```bash npm install ws ``` -------------------------------- ### Complete Extension Negotiation Example Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/utilities.md Demonstrates how to set up a WebSocket server and handle incoming connections, including checking negotiated extensions and protocols. ```javascript const { WebSocketServer, extension, subprotocol } = require('ws'); const wss = new WebSocketServer({ port: 8080, perMessageDeflate: true }); wss.on('connection', (ws) => { // Check negotiated extensions console.log('Extensions:', ws.extensions); // Check protocol console.log('Protocol:', ws.protocol); }); ``` -------------------------------- ### Install Optional bufferutil for Performance Source: https://github.com/websockets/ws/blob/master/README.md Install the bufferutil module as an optional dependency to improve the performance of masking and unmasking WebSocket data. Prebuilt binaries are available for common platforms. ```bash npm install --save-optional bufferutil ``` -------------------------------- ### Handle Server Listening Event Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Emitted when the server starts listening for connections. This is useful for confirming the server has started, especially when created with a specific port. ```javascript wss.on('listening', () => { ... }) ``` ```javascript const wss = new WebSocketServer({ port: 8080 }); wss.on('listening', () => { console.log('Server started'); }); ``` -------------------------------- ### Protocol Selection with handleProtocols Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Demonstrates how to use the `handleProtocols` hook to negotiate WebSocket subprotocols. This example prioritizes 'json' and 'msgpack' protocols, returning the selected protocol or `false` if none of the offered protocols are supported. ```javascript const { WebSocketServer } = require('ws'); const wss = new WebSocketServer({ port: 8080, handleProtocols: (protocols) => { if (protocols.has('json')) return 'json'; if (protocols.has('msgpack')) return 'msgpack'; return false; } }); wss.on('connection', (ws) => { console.log('Using protocol:', ws.protocol); }); ``` -------------------------------- ### Implement WebSocket Server Client Verification Source: https://github.com/websockets/ws/blob/master/_autodocs/errors.md This example demonstrates how to implement the `verifyClient` hook in a WebSocket server to control which clients can connect. It shows how to reject connections based on the presence of a valid token and allowed origin, returning appropriate HTTP status codes and reasons. ```javascript new WebSocketServer({ verifyClient: (info, callback) => { // Reject unauthorized if (!hasValidToken(info.req)) { return callback(false, 401, 'Unauthorized'); } // Reject based on origin if (info.origin !== 'https://trusted.example.com') { return callback(false, 403, 'Origin not allowed'); } // Accept callback(true); } }); ``` -------------------------------- ### server.handleUpgrade Source: https://github.com/websockets/ws/blob/master/doc/ws.md Handles an incoming HTTP upgrade request to establish a WebSocket connection. This method is crucial for manually managing WebSocket connections when not using the default server setup. ```APIDOC ## server.handleUpgrade(request, socket, head, callback) ### Description Handles 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. ### Method `server.handleUpgrade` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `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} - A callback function that is called with `websocket` and `request` arguments upon successful upgrade. ### Callback Arguments - `websocket` {WebSocket} - A `WebSocket` object representing the established connection. - `request` {http.IncomingMessage} - The client HTTP GET request. ### Request Example ```javascript // Example usage within a custom HTTP server setup server.on('upgrade', (request, socket, head) => { wsServer.handleUpgrade(request, socket, head, (websocket, request) => { // Handle the new WebSocket connection websocket.on('message', (message) => { console.log(`Received message: ${message}`); }); }); }); ``` ### Response #### Success Response Upon successful upgrade, the `callback` function is invoked with `websocket` and `request` arguments. #### Response Example (Callback function execution, no direct HTTP response) ### Error Handling Errors during the upgrade process are typically handled by the underlying HTTP server or by the `wsServer` instance itself, potentially emitting events like `'error'` or `'wsClientError'`. ``` -------------------------------- ### startLoop Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/receiver.md Starts or continues the frame parsing loop for WebSocket messages. This method is typically called internally by the `_write()` method. ```APIDOC ## startLoop() ### Description Start or continue the frame parsing loop. ### Method ```javascript receiver.startLoop(callback) ``` ### Parameters #### Path Parameters - **callback** (Function) - Callback when parsing is complete. ### Returns Undefined **Note:** Called internally by the `_write()` method. ``` -------------------------------- ### Simple WebSocket Server on Port Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md A basic WebSocket server setup that listens on a specified port. It handles incoming connections, logs received messages, broadcasts them to all connected clients, and logs disconnections. ```javascript const { WebSocketServer } = require('ws'); const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', (ws) => { console.log('Client connected'); ws.on('message', (data) => { console.log('Received:', data); // Broadcast to all clients wss.clients.forEach((client) => { if (client.readyState === ws.OPEN) { client.send(data); } }); }); ws.on('close', () => { console.log('Client disconnected'); }); }); ``` -------------------------------- ### Send Binary Data with WebSocket Source: https://github.com/websockets/ws/blob/master/README.md Example of sending binary data, specifically a Float32Array, over a WebSocket connection. ```javascript 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); }); ``` -------------------------------- ### Client Authentication with verifyClient Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Secures WebSocket connections by implementing authentication within the `verifyClient` hook. This example checks for a specific token in the `sec-websocket-protocol` header and rejects unauthorized clients. ```javascript const { WebSocketServer } = require('ws'); const wss = new WebSocketServer({ port: 8080, verifyClient: (info, callback) => { const token = info.req.headers['sec-websocket-protocol']; if (validateToken(token)) { callback(true); } else { callback(false, 401, 'Unauthorized'); } } }); wss.on('connection', (ws, req) => { ws.send('Authenticated!'); }); function validateToken(token) { // Your auth logic return true; } ``` -------------------------------- ### Direct Receiver Usage Example Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/receiver.md Demonstrates how to instantiate and use the Receiver class in server mode. It sets up event listeners for messages, pings, close events, and errors. In a real application, the receiver would typically pipe data from a socket. ```javascript const { Receiver } = require('ws'); const { Duplex } = require('stream'); const receiver = new Receiver({ isServer: true, maxPayload: 100 * 1024 * 1024, binaryType: 'nodebuffer' }); receiver.on('message', (data, isBinary) => { console.log('Message:', data); }); receiver.on('ping', (data) => { console.log('Ping:', data); }); receiver.on('conclude', (code, reason) => { console.log('Close:', code, reason.toString()); }); receiver.on('error', (err) => { console.error('Receiver error:', err); }); // In real usage, data comes from a socket // socket.pipe(receiver) ``` -------------------------------- ### Send and Receive Text Data with WebSocket Source: https://github.com/websockets/ws/blob/master/README.md Basic example of establishing a WebSocket connection, sending a text message, and handling incoming messages and errors. ```javascript 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); }); ``` -------------------------------- ### Broadcast Messages to All Clients Source: https://github.com/websockets/ws/blob/master/README.md This example demonstrates a server broadcasting received messages to all currently connected WebSocket clients. It ensures that messages are only sent to clients with an OPEN connection state. ```javascript 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 }); } }); }); }); ``` -------------------------------- ### Check WebSocket Ready State Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket.md Use `ws.readyState` to get the current connection state. It returns a number representing the state (CONNECTING, OPEN, CLOSING, CLOSED). ```javascript ws.readyState ``` ```javascript const ws = new WebSocket('ws://example.com'); ws.on('open', () => { if (ws.readyState === WebSocket.OPEN) { console.log('Connected'); } }); ``` -------------------------------- ### Start Frame Parsing Loop Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/receiver.md Initiates or continues the frame parsing loop. This method is called internally by `_write()` and accepts a callback function that is executed upon completion of parsing. ```javascript receiver.startLoop(callback) ``` -------------------------------- ### Get Client IP Address from X-Forwarded-For Header Source: https://github.com/websockets/ws/blob/master/README.md When a WebSocket server is behind a proxy, this example shows how to obtain the client's IP address from the 'X-Forwarded-For' HTTP header. It assumes the first IP in the list is the original client. ```javascript wss.on('connection', function connection(ws, req) { const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); ws.on('error', console.error); }); ``` -------------------------------- ### Set Up WebSocket Server Source: https://github.com/websockets/ws/blob/master/_autodocs/README.md This snippet shows how to create a WebSocket server that listens on a specified port, accepts client connections, and broadcasts received messages to all connected clients. ```javascript const { WebSocketServer } = require('ws'); const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', (ws) => { console.log('Client connected'); ws.on('message', (data) => { console.log('Received:', data); // Broadcast to all clients wss.clients.forEach((client) => { if (client.readyState === ws.OPEN) { client.send(data); } }); }); ws.on('close', () => { console.log('Client disconnected'); }); }); ``` -------------------------------- ### Install Optional utf-8-validate for Legacy Node.js Source: https://github.com/websockets/ws/blob/master/README.md For Node.js versions prior to v18.14.0, install the utf-8-validate module as an optional dependency. This provides a binary polyfill for buffer.isUtf8(). ```bash npm install --save-optional utf-8-validate ``` -------------------------------- ### Accept Compression Negotiation Offer Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/permessage-deflate.md Initialize PerMessageDeflate as a server and accept a peer's offer to negotiate compression parameters. ```javascript const pmd = new PerMessageDeflate({ isServer: true }); const peerOffer = [ { client_max_window_bits: 15, server_max_window_bits: true } ]; const accepted = pmd.accept(peerOffer); ``` -------------------------------- ### Instantiate WebSocketServer Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Create a new WebSocketServer instance. You can provide configuration options and an optional callback for the 'listening' event. ```javascript new WebSocketServer(options, [callback]) ``` -------------------------------- ### Get PerMessageDeflate Extension Name Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/permessage-deflate.md Access the static property to retrieve the official name of the permessage-deflate extension. ```javascript PerMessageDeflate.extensionName ``` -------------------------------- ### Connect to WebSocket Server (Client) Source: https://github.com/websockets/ws/blob/master/_autodocs/README.md This snippet demonstrates how to establish a WebSocket connection as a client, send messages, and handle incoming messages, connection status, and errors. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('ws://example.com/chat'); ws.on('open', () => { console.log('Connected'); ws.send('Hello Server!'); }); ws.on('message', (data) => { console.log('Received:', data); }); ws.on('close', (code, reason) => { console.log(`Closed: ${code} ${reason}`); }); ws.on('error', (error) => { console.error('Error:', error.message); }); ``` -------------------------------- ### Get Selected Subprotocol Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket.md Access `ws.protocol` to retrieve the subprotocol selected by the server. It will be an empty string if no subprotocol was negotiated. ```javascript ws.protocol ``` ```javascript const ws = new WebSocket('ws://example.com/chat', 'chat', 'superchat'); ws.on('open', () => { console.log('Selected protocol:', ws.protocol); // 'chat' or 'superchat' }); ``` -------------------------------- ### Configure WebSocket Client Options Source: https://github.com/websockets/ws/blob/master/_autodocs/configuration.md Instantiate a WebSocket client with various options for compression, message limits, handshake, TLS/SSL, and networking. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('ws://example.com/chat', 'chat', { // Compression perMessageDeflate: { clientMaxWindowBits: 15, clientNoContextTakeover: false, serverMaxWindowBits: 15, serverNoContextTakeover: false, serverWindow: 10, concurrencyLimit: 10, threshold: 1024, zlibDeflateOptions: { chunkSize: 1024, memLevel: 7, level: 3 }, zlibInflateOptions: { chunkSize: 10 * 1024 } }, // Message limits maxPayload: 100 * 1024 * 1024, // 100MB maxBufferedChunks: 1024 * 1024, // 1M chunks maxFragments: 128 * 1024, // 128K fragments // Handshake handshakeTimeout: 5000, // 5 seconds skipUTF8Validation: false, protocolVersion: 13, // HTTP/HTTPS headers: { 'X-Custom-Header': 'value', 'Authorization': 'Bearer token' }, origin: 'https://example.com', checkServerIdentity: (servername, cert) => { // Custom certificate validation return null; // null = valid, Error = invalid }, // TLS/SSL (for wss://) rejectUnauthorized: true, // Reject self-signed ca: fs.readFileSync('ca-cert.pem'), key: fs.readFileSync('client-key.pem'), cert: fs.readFileSync('client-cert.pem'), passphrase: 'key-password', // Networking agent: new https.Agent({ keepAlive: true, keepAliveMsecs: 1000 }), family: 0, // 4=IPv4, 6=IPv6, 0=both localAddress: '192.168.1.100' // Bind to specific address }); ``` -------------------------------- ### Access binaryType Property Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/receiver.md Get or set the format for binary message payloads. This property can be modified after the Receiver instance is created. ```javascript receiver.binaryType ``` -------------------------------- ### Basic WebSocket Connection and Messaging Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket.md Demonstrates how to establish a WebSocket connection, send messages, and handle incoming messages, connection open/close events, and errors. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('ws://example.com/chat'); ws.on('open', () => { console.log('Connected'); ws.send('Hello!'); }); ws.on('message', (data) => { console.log('Received:', data); }); ws.on('close', () => { console.log('Disconnected'); }); ws.on('error', (err) => { console.error('Error:', err); }); ``` -------------------------------- ### Get Negotiated Extensions Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket.md Check `ws.extensions` for a comma-separated string of active negotiated extensions. It's an empty string if none are used. ```javascript ws.extensions ``` ```javascript ws.on('open', () => { console.log('Extensions:', ws.extensions); // 'permessage-deflate' or '' }); ``` -------------------------------- ### accept(configurations) Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/permessage-deflate.md Accepts and negotiates compression parameters based on the offer(s) received from the peer. ```APIDOC ### accept(configurations) `instance.accept(configurations)` Accept and negotiate compression parameters based on the offer(s) from the peer. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | configurations | Array | Yes | Array of parameter objects from peer. | **Returns:** Object - The accepted configuration parameters. ```javascript const pmd = new PerMessageDeflate({ isServer: true }); const peerOffer = [ { client_max_window_bits: 15, server_max_window_bits: true } ]; const accepted = pmd.accept(peerOffer); ``` ``` -------------------------------- ### open Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket.md Emitted when the WebSocket connection is successfully established. ```APIDOC ## Event: open ### Description Emitted when the connection is established. ### Usage ```javascript ws.on('open', () => { ... }) ``` ``` -------------------------------- ### WebSocketServer Constructor Source: https://github.com/websockets/ws/blob/master/doc/ws.md Initializes a new WebSocketServer instance. It can optionally accept configuration options and a callback function to be executed upon successful server creation. ```APIDOC ## new WebSocketServer(options[, callback]) ### Description Constructs a new WebSocket server instance. The `options` object can be used to configure server behavior, and the `callback` function is invoked when the server is ready. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (object) - Optional - Configuration options for the WebSocket server. - **callback** (function) - Optional - A function to be called when the server starts listening. ``` -------------------------------- ### Server-Side Stream Wrapping Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/stream.md Wraps an incoming WebSocket connection with a duplex stream on the server side. This example creates a simple echo server using streams. ```javascript const http = require('http'); const { WebSocketServer, createWebSocketStream } = require('ws'); const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', (ws) => { const duplex = createWebSocketStream(ws); // Echo server using streams duplex.pipe(duplex); }); ``` -------------------------------- ### offer() Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/permessage-deflate.md Creates a compression negotiation offer to be sent in the Sec-WebSocket-Extensions header. ```APIDOC ## Instance Methods ### offer() `instance.offer()` Create a compression negotiation offer for the client or server. **Returns:** Object - Parameters to be sent in `Sec-WebSocket-Extensions` header. ```javascript const pmd = new PerMessageDeflate({ clientNoContextTakeover: true }); const offer = pmd.offer(); // offer = { client_no_context_takeover: true } ``` ``` -------------------------------- ### Create a Simple WebSocket Server Source: https://github.com/websockets/ws/blob/master/README.md A basic WebSocket server that listens on port 8080, handles connections, and logs received messages. ```javascript 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'); }); ``` -------------------------------- ### Create Compression Negotiation Offer Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/permessage-deflate.md Instantiate PerMessageDeflate and generate an offer object to be sent in the Sec-WebSocket-Extensions header for negotiation. ```javascript const pmd = new PerMessageDeflate({ clientNoContextTakeover: true }); const offer = pmd.offer(); // offer = { client_no_context_takeover: true } ``` -------------------------------- ### WebSocketServer Constructor Source: https://github.com/websockets/ws/blob/master/doc/ws.md Instantiates a new WebSocket server. Requires either a port, a pre-created HTTP/S server, or 'noServer' mode to be enabled. Options can be provided to customize server behavior. ```APIDOC ## new WebSocketServer(options[, callback]) ### Description Creates 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. ### Parameters #### options {Object} - `allowSynchronousEvents` (Boolean) - Specifies whether any of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple times in the same tick. Defaults to `true`. - `autoPong` (Boolean) - Specifies whether or not to automatically send a pong in response to a ping. Defaults to `true`. - `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 after [`websocket.close()`](#websocketclose) is called. Defaults to 30000. - `handleProtocols` (Function) - A function which can be used to handle the WebSocket subprotocols. - `host` (String) - The hostname where to bind the server. - `maxBufferedChunks` (Number) - The maximum number of buffered data chunks. Defaults to 1048576. Set to 0 to disable the limit. - `maxFragments` (Number) - The maximum number of fragments in a message. Defaults to 131072. Set to 0 to disable the limit. - `maxPayload` (Number) - The maximum allowed message size in bytes. 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 to `false`. - `verifyClient` (Function) - A function which can be used to validate incoming connections. (Usage is discouraged: see [Issue #337](https://github.com/websockets/ws/issues/377#issuecomment-462152231)) - `WebSocket` (Function) - Specifies the `WebSocket` class to be used. Defaults to `WebSocket`. #### callback {Function} ### Usage Notes - Use of `verifyClient` is discouraged. Rather handle client authentication in the `'upgrade'` event of the HTTP server. - If `verifyClient` is not set, then the handshake is automatically accepted. - If `verifyClient` has a single parameter, it is invoked with `info` {Object}. - If `verifyClient` has two parameters, it is invoked with `info` {Object} and `cb` {Function}. - `handleProtocols` takes `protocols` {Set} and `request` {http.IncomingMessage} as arguments. ``` -------------------------------- ### Use Node.js Streams with WebSockets Source: https://github.com/websockets/ws/blob/master/README.md This example demonstrates integrating WebSockets with Node.js streams using `createWebSocketStream`. It pipes data from standard input to the WebSocket and from the WebSocket to standard output. ```javascript 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); ``` -------------------------------- ### Configure WebSocketServer with Manual Upgrade Handling Source: https://github.com/websockets/ws/blob/master/_autodocs/configuration.md Use this option when you need to manually handle incoming upgrade requests. This provides fine-grained control over the connection process. ```javascript const wss = new WebSocketServer({ noServer: true }); server.on('upgrade', (req, socket, head) => { wss.handleUpgrade(req, socket, head, (ws) => { wss.emit('connection', ws, req); }); }); ``` -------------------------------- ### Binary Data Handling with Buffers Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/utilities.md Illustrates how to handle binary data, including receiving data as ArrayBuffer and sending various data types like Buffers, TypedArrays, and strings. ```javascript const { toBuffer, toArrayBuffer } = require('./lib/buffer-util'); // Receive as ArrayBuffer ws.binaryType = 'arraybuffer'; ws.on('message', (arrayBuffer) => { // Convert to Buffer for processing const buffer = toBuffer(arrayBuffer); console.log('Buffer:', buffer); // Or keep as ArrayBuffer const view = new Uint16Array(arrayBuffer); }); // Send different data types ws.send(Buffer.from('buffer data')); ws.send(new Uint8Array([1, 2, 3])); ws.send('string data'); ``` -------------------------------- ### Get Git Commit Author Email Source: https://github.com/websockets/ws/blob/master/SECURITY.md Use this command to retrieve the author's name and email from the latest git commit. This is useful for finding contact information for lead developers. ```bash git --no-pager show -s --format='%an <%ae>' ``` -------------------------------- ### Project File Organization Source: https://github.com/websockets/ws/blob/master/_autodocs/README.md This snippet outlines the directory structure of the ws project, showing the location of various documentation files and internal API references. ```text /workspace/home/output/ ├── README.md ← This file ├── types.md ← Type definitions ├── configuration.md ← Configuration options ├── errors.md ← Error handling └── api-reference/ ├── websocket.md ← WebSocket class ├── websocket-server.md ← WebSocketServer class ├── permessage-deflate.md ← Compression extension ├── receiver.md ← Frame parsing (internal) ├── sender.md ← Frame construction (internal) ├── stream.md ← Duplex stream wrapper └── utilities.md ← Helper functions ``` -------------------------------- ### Get Server Address Information Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Obtain the bound address, port, and address family of the running WebSocket server. This is useful for logging or external monitoring. Throws an error if the server is in 'noServer' mode. ```javascript wss.address() ``` ```javascript const wss = new WebSocketServer({ port: 8080 }); wss.on('listening', () => { const addr = wss.address(); console.log(`Server listening at ${addr.address}:${addr.port}`); }); ``` -------------------------------- ### Get Client IP Address from Raw Socket Source: https://github.com/websockets/ws/blob/master/README.md This snippet shows how to retrieve the remote IP address of a connected client directly from the raw socket object available in the 'connection' event handler. ```javascript 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); }); ``` -------------------------------- ### Client WebSocket Connection Lifecycle Source: https://github.com/websockets/ws/blob/master/_autodocs/README.md Illustrates the state transitions of a WebSocket client connection, from initial connection to closure. Useful for understanding client-side connection management. ```text [Constructor] ↓ CONNECTING ← Waiting for handshake ↓ OPEN ← Ready to send/receive ↓ ↓ (either) CLOSING ← Handshake in progress ↓ CLOSED ← Connection terminated ``` -------------------------------- ### Import WebSocket, Server, and Stream Utilities (ES Module) Source: https://github.com/websockets/ws/blob/master/_autodocs/README.md This snippet demonstrates how to import the WebSocket class, WebSocketServer, and createWebSocketStream utility from the ws library using ES Module syntax. ```javascript import WebSocket, { WebSocketServer, createWebSocketStream } from 'ws'; const ws = new WebSocket('ws://example.com'); const wss = new WebSocketServer({ port: 8080 }); const stream = createWebSocketStream(ws); ``` -------------------------------- ### WebSocketClientOptions Configuration Source: https://github.com/websockets/ws/blob/master/_autodocs/types.md Constructor options for a client WebSocket instance. Includes settings for compression, subprotocol negotiation, HTTP headers, connection parameters, and TLS/SSL. ```javascript { // Compression perMessageDeflate: boolean | PerMessageDeflateOptions, // Subprotocol negotiation protocol: string | string[], // HTTP headers headers: { [key: string]: string }, origin: string, // Connection settings handshakeTimeout: number, // Timeout in milliseconds maxPayload: number, // Max message size maxBufferedChunks: number, // Max buffered chunks maxFragments: number, // Max message fragments // TLS/SSL options (for wss://) rejectUnauthorized: boolean, // Reject self-signed certs (default true) checkServerIdentity: function, // Custom certificate verification key: Buffer | string, // Client certificate key cert: Buffer | string, // Client certificate ca: Buffer[] | Buffer | string, // CA certificates passphrase: string, // Private key passphrase // Proxy & connection agent: http.Agent | https.Agent, family: 4 | 6 | 0, // IP family (default 0 = both) localAddress: string, // Local address to bind // Validation skipUTF8Validation: boolean, // Skip UTF-8 checks (default false) // Protocol version protocolVersion: 8 | 13 // WebSocket version (default 13) } ``` -------------------------------- ### Instantiate PerMessageDeflate Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/permessage-deflate.md Create a new instance of the PerMessageDeflate class. Options can be provided to configure its behavior, such as specifying server or client mode, compression thresholds, and zlib settings. ```javascript new PerMessageDeflate([options]) ``` -------------------------------- ### Measure WebSocket Round-Trip Time Source: https://github.com/websockets/ws/blob/master/README.md This client-side example connects to a WebSocket server, sends the current timestamp, and calculates the round-trip time when the server echoes the timestamp back. It periodically sends new timestamps. ```javascript 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); }); ``` -------------------------------- ### handleUpgrade(req, socket, head, callback) Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Handles an HTTP Upgrade request, validating the handshake and creating a WebSocket instance. ```APIDOC ### handleUpgrade(req, socket, head, callback) ```javascript wss.handleUpgrade(req, socket, head, callback) ``` Handle an HTTP Upgrade request. Validates the WebSocket handshake and creates a WebSocket instance. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | req | http.IncomingMessage | Yes | The HTTP request. | | socket | Duplex | Yes | The network socket. | | head | Buffer | Yes | The first packet of the upgraded stream. | | callback | Function | Yes | Called with `(ws, req)` on successful upgrade. | **Returns:** Undefined **Validation Steps:** 1. Checks HTTP method is GET 2. Validates Upgrade header 3. Validates Sec-WebSocket-Key 4. Validates Sec-WebSocket-Version 5. Checks path matches filter 6. Parses subprotocols 7. Parses extension offers 8. Calls `verifyClient` hook if defined 9. Calls `handleProtocols` hook if defined 10. Emits 101 Switching Protocols response ```javascript const http = require('http'); const { WebSocketServer } = require('ws'); const server = http.createServer(); const wss = new WebSocketServer({ noServer: true }); server.on('upgrade', (req, socket, head) => { wss.handleUpgrade(req, socket, head, (ws) => { console.log('Client connected'); ws.send('Welcome!'); }); }); server.listen(8080); ``` ``` -------------------------------- ### new WebSocket(address, protocols, options) Source: https://github.com/websockets/ws/blob/master/doc/ws.md Creates a new WebSocket instance to establish a connection to a specified address. It supports various options to customize connection behavior, security, and message handling. ```APIDOC ## new WebSocket(address, protocols, options) ### Description Creates a new WebSocket instance to establish a connection to a specified address. It supports various options to customize connection behavior, security, and message handling. ### Parameters #### Path Parameters - **address** (String|url.URL) - Required - The URL to which to connect. - **protocols** (String|Array) - Optional - The list of subprotocols. - **options** (Object) - Optional - Configuration options for the WebSocket connection. - **allowSynchronousEvents** (Boolean) - Optional - Specifies whether any of the 'message', 'ping', and 'pong' events can be emitted multiple times in the same tick. Defaults to `true`. - **autoPong** (Boolean) - Optional - Specifies whether or not to automatically send a pong in response to a ping. Defaults to `true`. - **closeTimeout** (Number) - Optional - Duration in milliseconds to wait for a graceful close after `websocket.close()` is called. Defaults to 30000. - **finishRequest** (Function) - Optional - A function which can be used to customize the headers of each HTTP request before it is sent. - **followRedirects** (Boolean) - Optional - Whether or not to follow redirects. Defaults to `false`. - **generateMask** (Function) - Optional - The function used to generate the masking key. - **handshakeTimeout** (Number) - Optional - Timeout in milliseconds for the handshake request. - **maxBufferedChunks** (Number) - Optional - The maximum number of buffered data chunks. Defaults to 1048576. - **maxFragments** (Number) - Optional - The maximum number of fragments in a message. Defaults to 131072. - **maxPayload** (Number) - Optional - The maximum allowed message size in bytes. Defaults to 104857600. - **maxRedirects** (Number) - Optional - The maximum number of redirects allowed. Defaults to 10. - **origin** (String) - Optional - Value of the `Origin` or `Sec-WebSocket-Origin` header. - **perMessageDeflate** (Boolean|Object) - Optional - Enable/disable permessage-deflate. Defaults to `true`. - **protocolVersion** (Number) - Optional - Value of the `Sec-WebSocket-Version` header. - **skipUTF8Validation** (Boolean) - Optional - Specifies whether or not to skip UTF-8 validation for text and close messages. Defaults to `false`. - Any other option allowed in `http.request()` or `https.request()`. ### IPC connections `ws` supports IPC connections. To connect to an IPC endpoint, use the following URL form: - On Unices: ``` ws+unix:/absolute/path/to/uds_socket:/pathname?search_params ``` - On Windows: ``` ws+unix:\\.\pipe\pipe_name:/pathname?search_params ``` The character `:` is the separator between the IPC path and the URL path. The IPC path must not include the characters `:` and `?`. ### Event: 'close' - `code` (Number) - The status code explaining why the connection has been closed. - `reason` (Buffer) - A human-readable string explaining why the connection has been closed. Emitted when the connection is closed. ### Event: 'error' - `error` (Error) - The error object. Emitted when an error occurs. Errors may have a `.code` property. ### Event: 'message' - `data` (ArrayBuffer|Blob|Buffer|Buffer[]) - The message content. - `isBinary` (Boolean) - Specifies whether the message is binary or not. Emitted when a message is received. ### Event: 'open' Emitted when the connection is established. ``` -------------------------------- ### WebSocketServerOptions Source: https://github.com/websockets/ws/blob/master/_autodocs/types.md Constructor options for configuring a WebSocket server, including binding, client limits, features, and hooks. ```APIDOC ## WebSocketServerOptions Constructor options for WebSocket server. ### Parameters #### Server Binding (exactly one required) - **port** (number) - Port to listen on - **server** (http.Server | https.Server) - Existing server - **noServer** (boolean) - Don't create/attach server #### Server Configuration - **host** (string) - Hostname to bind - **path** (string) - Path filter - **backlog** (number) - Queue length (default 511) #### Client Limits - **maxPayload** (number) - Max message size (100MB default) - **maxBufferedChunks** (number) - Max buffered chunks (1M default) - **maxFragments** (number) - Max fragments (128K default) - **closeTimeout** (number) - Close handshake timeout (30s default) #### Features - **perMessageDeflate** (boolean | PerMessageDeflateOptions) - Compression - **clientTracking** (boolean) - Track clients in wss.clients (default true) - **allowSynchronousEvents** (boolean) - Sync event emission (default true) - **autoPong** (boolean) - Auto-respond to pings (default true) - **skipUTF8Validation** (boolean) - Skip UTF-8 validation (default false) #### Hooks - **handleProtocols** (function) - Select subprotocol - **verifyClient** (function) - Verify/reject connection - **WebSocket** (WebSocket) - Custom WebSocket class #### Protocol Version - **protocolVersion** (8 | 13) - WebSocket version (default 13) ``` -------------------------------- ### WebSocketServer Constructor Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Initializes a new WebSocketServer instance. It handles HTTP upgrade requests and manages client connections, extending EventEmitter. ```APIDOC ## WebSocketServer Constructor ### Description Initializes a new WebSocketServer instance. It handles HTTP upgrade requests and manages client connections, extending EventEmitter. ### Method Signature `new WebSocketServer(options, [callback])` ### Parameters #### Path Parameters - **options** (Object) - Required - Server configuration options. - **callback** (Function) - Optional - Listener for the `'listening'` event. ### Options #### Port - **port** (Number) - Optional - Port to listen on. Mutually exclusive with `server` and `noServer`. #### Server - **server** (http.Server or https.Server) - Optional - Existing HTTP/S server to attach to. Mutually exclusive with `port` and `noServer`. #### No Server - **noServer** (Boolean) - Optional - Don't create or attach to an HTTP server. Mutually exclusive with `port` and `server`. #### Host - **host** (String) - Optional - Hostname to bind to (used with `port`). #### Path - **path** (String) - Optional - Accept only connections matching this path. #### Backlog - **backlog** (Number) - Optional - Queue length for pending connections. Default: 511. #### Per Message Deflate - **perMessageDeflate** (Boolean or Object) - Optional - Enable compression. Pass object to configure (see PerMessageDeflate). Default: false. #### Client Tracking - **clientTracking** (Boolean) - Optional - Track connected clients in `wss.clients` Set. Default: true. #### Max Payload - **maxPayload** (Number) - Optional - Maximum allowed message size in bytes (100MB). Default: 104857600. #### Max Buffered Chunks - **maxBufferedChunks** (Number) - Optional - Maximum number of buffered data chunks. Default: 1048576. #### Max Fragments - **maxFragments** (Number) - Optional - Maximum number of message fragments. Default: 131072. #### Skip UTF-8 Validation - **skipUTF8Validation** (Boolean) - Optional - Skip UTF-8 validation for text and close messages. Default: false. #### Allow Synchronous Events - **allowSynchronousEvents** (Boolean) - Optional - Allow `'message'`, `'ping'`, `'pong'` events in same tick. Default: true. #### Auto Pong - **autoPong** (Boolean) - Optional - Automatically respond to pings with pongs. Default: true. #### Close Timeout - **closeTimeout** (Number) - Optional - Time to wait for close handshake. Default: 30000. #### Handle Protocols - **handleProtocols** (Function) - Optional - Hook to select subprotocol from client offers. Default: null. #### Verify Client - **verifyClient** (Function) - Optional - Hook to verify/reject connections. Default: null. #### WebSocket - **WebSocket** (Class) - Optional - Custom WebSocket class (must extend WebSocket). Default: WebSocket. ``` -------------------------------- ### No Server Mode with Multiple Paths Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Configures multiple WebSocket servers to handle different paths on a single HTTP server without explicitly creating a WebSocket server instance. The `handleUpgrade` method is used to delegate incoming upgrade requests to the appropriate WebSocket server based on the request URL. ```javascript const http = require('http'); const { WebSocketServer } = require('ws'); const server = http.createServer(); const wss1 = new WebSocketServer({ noServer: true }); const wss2 = new WebSocketServer({ noServer: true }); wss1.on('connection', (ws) => { console.log('Chat connected'); }); wss2.on('connection', (ws) => { console.log('Game connected'); }); server.on('upgrade', (req, socket, head) => { if (req.url === '/chat') { wss1.handleUpgrade(req, socket, head, (ws) => { wss1.emit('connection', ws, req); }); } else if (req.url === '/game') { wss2.handleUpgrade(req, socket, head, (ws) => { wss2.emit('connection', ws, req); }); } else { socket.destroy(); } }); server.listen(8080); ``` -------------------------------- ### Create and Manage WebSocket Stream Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/stream.md Demonstrates how to create a duplex stream from a WebSocket instance and manage its lifecycle, including destruction and listening for close events on both the stream and the WebSocket. ```javascript const WebSocket = require('ws'); const { createWebSocketStream } = require('ws'); const ws = new WebSocket('ws://example.com'); const duplex = createWebSocketStream(ws); // Order of events during cleanup: duplex.destroy(); // Calls ws.terminate() duplex.on('close', () => { console.log('Duplex closed'); }); ws.on('close', () => { console.log('WebSocket closed'); }); ``` -------------------------------- ### WebSocket Constructor Source: https://github.com/websockets/ws/blob/master/doc/ws.md Creates a new WebSocket client instance to connect to a specified server address. It supports optional protocols and connection options. ```APIDOC ## new WebSocket(address[, protocols][, options]) ### Description Establishes a new WebSocket connection to the specified `address`. You can provide an array of `protocols` to negotiate, and an `options` object for advanced configuration. ### Parameters - **address** (string | URL) - The URL of the WebSocket server to connect to. - **protocols** (string | string[]) - Optional. A list of supported subprotocols. - **options** (object) - Optional. Configuration options for the WebSocket client. ``` -------------------------------- ### Import WebSocket, Server, and Stream Utilities (CommonJS) Source: https://github.com/websockets/ws/blob/master/_autodocs/README.md This snippet shows how to import the main WebSocket class, WebSocketServer, and createWebSocketStream utility from the ws library using CommonJS module syntax. ```javascript const WebSocket = require('ws'); // Default export is the WebSocket class const ws = new WebSocket('ws://example.com'); // Access server class const { WebSocketServer } = WebSocket; const wss = new WebSocketServer({ port: 8080 }); // Access utility functions const { createWebSocketStream, extension, subprotocol } = WebSocket; ``` -------------------------------- ### WebSocket Constructor Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket.md Instantiates a new WebSocket connection. The address parameter is the URL to connect to, protocols are optional subprotocols, and options allow for connection configuration. ```javascript new WebSocket(address, [protocols], [options]) ``` -------------------------------- ### address() Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Returns the bound address, port, and address family of the server. ```APIDOC ## Instance Methods ### address() ```javascript wss.address() ``` Returns the bound address, port, and address family of the server. **Returns:** Object or String or null **Throws:** Error if server is in `noServer` mode. | Property | |----------| | address | String | IP address (e.g., '127.0.0.1') | | family | String | Address family ('IPv4' or 'IPv6') | | port | Number | Port number | ```javascript const wss = new WebSocketServer({ port: 8080 }); wss.on('listening', () => { const addr = wss.address(); console.log(`Server listening at ${addr.address}:${addr.port}`); }); ``` ``` -------------------------------- ### Instance Properties Source: https://github.com/websockets/ws/blob/master/_autodocs/api-reference/websocket-server.md Properties available on the WebSocket Server instance. ```APIDOC ## Instance Properties ### clients ```javascript wss.clients ``` **Type:** Set or undefined **Read-only:** Yes Set of currently connected WebSocket instances. Undefined if `clientTracking` is false. ```javascript wss.on('connection', (ws) => { console.log('Total clients:', wss.clients.size); // Broadcast to all clients wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send('Hello everyone!'); } }); }); ``` ### options ```javascript wss.options ``` **Type:** Object **Read-only:** Yes The merged options used to create the server. ```