### Full WebSocket Server Usage Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketRequest.md A comprehensive example demonstrating how to set up a WebSocket server, handle incoming requests, perform origin and protocol checks, and manage connections. ```javascript var WebSocketServer = require('websocket').server; var http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(404); res.end(); }); var wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); wsServer.on('request', function(request) { // Inspect the request console.log('New request from:', request.remoteAddress); console.log('Origin:', request.origin); console.log('Requested protocols:', request.requestedProtocols); console.log('Resource:', request.resource); // Check origin security if (request.origin !== 'http://localhost') { console.log('Origin not allowed'); request.reject(); return; } // Check requested protocol var protocol; if (request.requestedProtocols.indexOf('echo') !== -1) { protocol = 'echo'; } else if (request.requestedProtocols.length === 0) { protocol = null; } else { console.log('Protocol not supported'); request.reject(); return; } // Accept and establish connection var connection = request.accept(protocol, request.origin); console.log('Connection accepted'); connection.on('message', function(message) { if (message.type === 'utf8') { console.log('Received:', message.utf8Data); connection.sendUTF(message.utf8Data); // Echo back } }); connection.on('close', function() { console.log('Connection closed'); }); }); server.listen(8080); ``` -------------------------------- ### Full WebSocket Server Usage Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketServer.md A complete example demonstrating how to set up a WebSocket server, handle incoming connections, process messages, and manage connection closures. It includes server initialization with specific configurations and event listeners for requests, messages, and connection closures. ```javascript var WebSocketServer = require('websocket').server; var http = require('http'); var httpServer = http.createServer(function(request, response) { response.writeHead(404); response.end(); }); var wsServer = new WebSocketServer({ httpServer: httpServer, autoAcceptConnections: false, maxReceivedFrameSize: 64 * 1024, maxReceivedMessageSize: 8 * 1024 * 1024 }); wsServer.on('request', function(request) { console.log('New connection from:', request.remoteAddress); var connection = request.accept('chat', request.origin); connection.on('message', function(message) { if (message.type === 'utf8') { wsServer.broadcastUTF(message.utf8Data); } }); connection.on('close', function() { console.log('Connection closed'); }); }); httpServer.listen(8080); ``` -------------------------------- ### WebSocket Client Configuration Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Example demonstrating various client configuration options, including message size limits, fragmentation settings, and TLS options. ```javascript var client = new WebSocketClient({ maxReceivedFrameSize: 256 * 1024, // 256 KiB maxReceivedMessageSize: 16 * 1024 * 1024, // 16 MiB fragmentOutgoingMessages: true, webSocketVersion: 13, // RFC 6455 assembleFragments: true, disableNagleAlgorithm: true, closeTimeout: 5000, tlsOptions: { ca: [fs.readFileSync('ca.pem')], rejectUnauthorized: true, minVersion: 'TLSv1.2' } }); ``` -------------------------------- ### Full WebSocket Server Usage Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketConnection.md This example demonstrates setting up an HTTP server and a WebSocket server, accepting client connections, handling incoming messages (UTF-8), echoing them back, and managing connection events like 'ping', 'close', and 'error'. It also sends an initial welcome message to the client. ```javascript var WebSocketServer = require('websocket').server; var http = require('http'); var server = http.createServer(); var wsServer = new WebSocketServer({ httpServer: server }); wsServer.on('request', function(request) { var connection = request.accept(); console.log('Client connected from', connection.remoteAddress); connection.on('message', function(message) { if (message.type === 'utf8') { console.log('Received:', message.utf8Data); // Echo message back connection.sendUTF('Echo: ' + message.utf8Data); } }); connection.on('ping', function(cancel, payload) { console.log('Ping received, sending pong'); }); connection.on('close', function(code, desc) { console.log('Client disconnected:', code, desc); }); connection.on('error', function(error) { console.error('Error:', error); }); // Send a welcome message connection.sendUTF('Welcome to the server!'); }); server.listen(8080); ``` -------------------------------- ### Install websocket-node Source: https://github.com/theturtle32/websocket-node/blob/master/README.md Install the websocket library using npm. This is the first step before requiring its modules in your project. ```bash $ npm install websocket ``` -------------------------------- ### Basic W3CWebSocket Usage Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/W3CWebSocket.md A fundamental example showing how to establish a WebSocket connection, send messages, and handle incoming messages and connection events. It includes sending periodic 'Ping' messages. ```javascript var W3CWebSocket = require('websocket').w3cwebsocket; var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol'); client.onerror = function() { console.log('Connection error'); }; client.onopen = function() { console.log('WebSocket connected'); // Send a message client.send('Hello Server!'); // Send some data periodically setInterval(function() { if (client.readyState === client.OPEN) { client.send('Ping'); } }, 5000); }; client.onclose = function() { console.log('WebSocket closed'); }; client.onmessage = function(e) { console.log('Received: ' + e.data); }; ``` -------------------------------- ### WebSocketRouter Configuration Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Demonstrates configuring a WebSocketRouter, either by passing a server instance during construction or by attaching it later. ```javascript var router = new WebSocketRouter({ server: wsServer }); // Or attach later var router = new WebSocketRouter(); router.attachServer(wsServer); ``` -------------------------------- ### Secure WebSocket Server (HTTPS) Setup Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Example of setting up a secure WebSocket server using Node.js HTTPS module. This is required for wss:// connections. ```javascript var https = require('https'); var fs = require('fs'); var WebSocketServer = require('websocket').server; var httpsServer = https.createServer({ key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-cert.pem') }); var wsServer = new WebSocketServer({ httpServer: httpsServer }); httpsServer.listen(8443); ``` -------------------------------- ### Full WebSocket Server with Routing Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketRouter.md Sets up a complete WebSocket server using 'websocket' library, including HTTP server creation, router instantiation, mounting handlers for different paths and protocols, and a catch-all handler. ```javascript var WebSocketServer = require('websocket').server; var WebSocketRouter = require('websocket').router; var http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(404); res.end(); }); var wsServer = new WebSocketServer({ httpServer: server }); // Create and attach router var router = new WebSocketRouter({ server: wsServer }); // Mount handlers for different paths and protocols router.mount('/chat', 'chat', function(request) { console.log('Chat request'); var connection = request.accept('chat'); connection.on('message', function(message) { if (message.type === 'utf8') { // Broadcast to all chat connections wsServer.broadcastUTF('[' + connection.remoteAddress + '] ' + message.utf8Data); } }); }); router.mount('/api', 'json-rpc', function(request) { console.log('API request'); var connection = request.accept('json-rpc'); connection.on('message', function(message) { if (message.type === 'utf8') { try { var data = JSON.parse(message.utf8Data); // Process RPC call connection.sendUTF(JSON.stringify({ result: 'ok' })); } catch (e) { connection.sendUTF(JSON.stringify({ error: 'Invalid JSON' })); } } }); }); // Mount a catch-all handler for other paths router.mount('*', '*', function(request) { console.log('Unknown path:', request.resource); request.reject(404, 'Path not found'); }); server.listen(8080, function() { console.log('Server listening on port 8080'); console.log('Available paths: /chat (chat), /api (json-rpc)'); }); ``` -------------------------------- ### Server-Side WebSocket Setup Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/README.md Set up a WebSocket server that listens for incoming connections and handles messages. Ensure an HTTP server is already running. ```javascript var WebSocketServer = require('websocket').server; var wsServer = new WebSocketServer({ httpServer: httpServer, autoAcceptConnections: false }); wsServer.on('request', function(request) { var connection = request.accept(); connection.on('message', function(message) { if (message.type === 'utf8') { console.log(message.utf8Data); } }); }); ``` -------------------------------- ### Handle Client Requested Protocols Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketRequest.md Example of how to access and use the client's requested protocols to conditionally accept a connection. ```javascript wsServer.on('request', function(request) { console.log('Client requested protocols:', request.requestedProtocols); if (request.requestedProtocols.indexOf('chat') !== -1) { var conn = request.accept('chat'); } else { request.reject(); } }); ``` -------------------------------- ### W3CWebSocket with Client Configuration Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Example of creating a W3CWebSocket instance with detailed client configuration, including WebSocket version and fragmentation settings. ```javascript var ws = new W3CWebSocket( 'wss://example.com/ws', ['chat', 'echo'], 'https://example.com', { 'X-Custom-Header': 'value' }, { timeout: 5000 }, // http/https.request options { // clientConfig webSocketVersion: 13, fragmentOutgoingMessages: true, tlsOptions: { rejectUnauthorized: true } } ); ``` -------------------------------- ### Advanced Chat Client Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/W3CWebSocket.md A comprehensive example demonstrating a chat client using W3CWebSocket. It includes features like joining a chat, sending messages, handling different message types, and automatic reconnection. ```javascript var W3CWebSocket = require('websocket').w3cwebsocket; class ChatClient { constructor(url, username) { this.url = url; this.username = username; this.ws = null; this.init(); } init() { this.ws = new W3CWebSocket(this.url, 'chat'); this.ws.onerror = () => { console.error('Connection error'); this.reconnect(); }; this.ws.onopen = () => { console.log('Connected to chat server'); this.send({ type: 'join', username: this.username }); }; this.ws.onclose = () => { console.log('Disconnected from chat'); }; this.ws.onmessage = (event) => { try { var msg = JSON.parse(event.data); this.handleMessage(msg); } catch (e) { console.error('Failed to parse message:', e); } }; } send(obj) { if (this.ws.readyState === this.ws.OPEN) { this.ws.send(JSON.stringify(obj)); } } sendChat(text) { this.send({ type: 'message', text: text }); } handleMessage(msg) { switch (msg.type) { case 'message': console.log(msg.username + ': ' + msg.text); break; case 'user-joined': console.log(msg.username + ' joined'); break; case 'user-left': console.log(msg.username + ' left'); break; } } reconnect() { setTimeout(() => { console.log('Attempting to reconnect...'); this.init(); }, 3000); } } // Usage var client = new ChatClient('ws://localhost:8080/', 'User123'); ``` -------------------------------- ### WebSocketRequest Requested Extensions Example Source: https://github.com/theturtle32/websocket-node/blob/master/docs/WebSocketRequest.md An example structure for the 'requestedExtensions' array, showing how extensions and their parameters might be represented. ```javascript [ { name: "simple-extension"; }, { name: "my-great-compression-extension", params: [ { name: "compressionLevel", value: "10"; } ] } ] ``` -------------------------------- ### Configure WebSocketServer Options Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md This example demonstrates setting various configuration options for a WebSocketServer, including message size limits, fragmentation, keepalive, and connection acceptance. ```javascript var server = new WebSocketServer({ httpServer: myHttpServer, maxReceivedFrameSize: 128 * 1024, // 128 KiB frames maxReceivedMessageSize: 10 * 1024 * 1024, // 10 MiB messages fragmentOutgoingMessages: true, fragmentationThreshold: 32 * 1024, // 32 KiB threshold keepalive: true, keepaliveInterval: 30000, // 30 seconds keepaliveGracePeriod: 5000, // 5 seconds grace assembleFragments: true, autoAcceptConnections: false, // Validate first! ignoreXForwardedFor: true, // Behind trusted proxy parseCookies: true, parseExtensions: false, // Don't need extensions disableNagleAlgorithm: true, closeTimeout: 10000 // 10 second close timeout }); ``` -------------------------------- ### WebSocketRequest Host Header Examples Source: https://github.com/theturtle32/websocket-node/blob/master/docs/WebSocketRequest.md Examples of the 'Host' header format received from the client, including domain names and port numbers. ```text www.example.com www.example.com:8080 127.0.0.1:3000 ``` -------------------------------- ### Internal Usage Example Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/Deprecation.md An example demonstrating the internal usage pattern of the Deprecation module. Direct application calls are not typical. ```javascript // Internal usage - not typically called directly by applications var Deprecation = require('websocket').deprecation; // The module would handle deprecation logging internally ``` -------------------------------- ### Basic WebSocket Server Setup Source: https://github.com/theturtle32/websocket-node/blob/master/README.md Sets up a basic HTTP server that listens on port 8080. A WebSocketServer is then attached to this HTTP server to handle WebSocket connections. ```javascript #!/usr/bin/env node var WebSocketServer = require('websocket').server; var http = require('http'); var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection ``` -------------------------------- ### LWS Mirror Protocol Client Setup Source: https://github.com/theturtle32/websocket-node/blob/master/test/scripts/libwebsockets-test.html Initializes a WebSocket connection for the 'lws-mirror-protocol' and sets up event listeners for mouse interactions on a canvas. Handles drawing, clearing, and color updates. ```javascript var ws_ctor = window['MozWebSocket'] ? window['MozWebSocket'] : window['WebSocket']; var socket_lm = new ws_ctor(get_appropriate_ws_url(), "lws-mirror-protocol"); var color = "#000000"; var lws_error = false; try { socket_lm.onopen = function() { document.getElementById("wslm_statustd").style.backgroundColor = "#40ff40"; document.getElementById("wslm_status").textContent = " websocket connection opened "; } socket_lm.onerror = function(error) { lws_error = true; document.getElementById("wslm_statustd").style.backgroundColor = "#ff4040"; document.getElementById("wslm_status").textContent = " websocket connection ERROR "; }; socket_lm.onmessage =function got_packet(msg) { j = msg.data.split(';'); f = 0; while (f < j.length - 1) { i = j[f].split(' '); if (i[0] == 'd') { ctx.strokeStyle = i[1]; ctx.beginPath(); ctx.moveTo(+(i[2]), +(i[3])); ctx.lineTo(+(i[4]), +(i[5])); ctx.stroke(); } if (i[0] == 'clear') { ctx.clearRect(0,0,480,300); } if (i[0] == 'c') { ctx.strokeStyle = i[1]; ctx.beginPath(); ctx.arc(+(i[2]), +(i[3]), +(i[4]), 0, Math.PI*2, true); ctx.stroke(); } f++; } } socket_lm.onclose = function(){ if (!lws_error) { document.getElementById("wslm_statustd").style.backgroundColor = "#ff4040"; document.getElementById("wslm_status").textContent = " websocket connection CLOSED "; } } } catch(exception) { alert('
Error' + exception); } ``` ```javascript var canvas = document.createElement('canvas'); canvas.height = 300; canvas.width = 480; ctx = canvas.getContext("2d"); document.getElementById('wslm_drawing').appendChild(canvas); canvas.addEventListener('mousemove', ev_mousemove, false); canvas.addEventListener('mousedown', ev_mousedown, false); canvas.addEventListener('mouseup', ev_mouseup, false); offsetX = offsetY = 0; element = canvas; if (element.offsetParent) { do { offsetX += element.offsetLeft; offsetY += element.offsetTop; } while ((element = element.offsetParent)); } function update_color() { color = document.getElementById("color").value; } function ev_mousedown (ev) { down = 1; } function ev_mouseup(ev) { down = 0; no_last = 1; } function ev_mousemove (ev) { var x, y; if (ev.offsetX) { x = ev.offsetX; y = ev.offsetY; } else { x = ev.layerX - offsetX; y = ev.layerY - offsetY; } if (!down) return; if (no_last) { no_last = 0; last_x = x; last_y = y; return; } if (socket_lm.readyState === ws_ctor.OPEN) socket_lm.send("d " + color + " " + last_x + " " + last_y + " " + x + ' ' + y + ';'); last_x = x; last_y = y; } function clearCanvas() { if (sock ``` -------------------------------- ### Node.js WebSocket Client Example Source: https://github.com/theturtle32/websocket-node/blob/master/README.md A basic Node.js client that connects to a WebSocket server, sends random numbers, and logs received messages. ```javascript #!/usr/bin/env node var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); client.on('connectFailed', function(error) { console.log('Connect Error: ' + error.toString()); }); client.on('connect', function(connection) { console.log('WebSocket Client Connected'); connection.on('error', function(error) { console.log("Connection Error: " + error.toString()); }); connection.on('close', function() { console.log('echo-protocol Connection Closed'); }); connection.on('message', function(message) { if (message.type === 'utf8') { console.log("Received: '" + message.utf8Data + "'"); } }); function sendNumber() { if (connection.connected) { var number = Math.round(Math.random() * 0xFFFFFF); connection.sendUTF(number.toString()); setTimeout(sendNumber, 1000); } } sendNumber(); }); client.connect('ws://localhost:8080/', 'echo-protocol'); ``` -------------------------------- ### W3C WebSocket API Client Example Source: https://github.com/theturtle32/websocket-node/blob/master/README.md A Node.js client using the W3C WebSocket API to connect, send data, and handle messages. ```javascript var W3CWebSocket = require('websocket').w3cwebsocket; var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol'); client.onerror = function() { console.log('Connection Error'); }; client.onopen = function() { console.log('WebSocket Client Connected'); function sendNumber() { if (client.readyState === client.OPEN) { var number = Math.round(Math.random() * 0xFFFFFF); client.send(number.toString()); setTimeout(sendNumber, 1000); } } sendNumber(); }; client.onclose = function() { console.log('echo-protocol Client Closed'); }; client.onmessage = function(e) { if (typeof e.data === 'string') { console.log("Received: '" + e.data + "'"); } }; ``` -------------------------------- ### Close Frame with Code and Reason Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketFrame.md Example of constructing a close frame with a status code and a UTF-8 encoded reason. The binary format and byte representation are shown. ```javascript // Close frame with code and reason // Binary format: [0x08][length][code_hi][code_lo][reason_utf8...] // Example: Close with 1000 (Normal) and "Goodbye" // [0x88][0x09][0x03][0xE8][G][o][o][d][b][y][e] // ^^^^ = 1000 in big-endian ``` -------------------------------- ### WebSocket Server Configuration for Production Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/README.md Configure a WebSocket server for production environments, utilizing HTTPS and disabling automatic connection acceptance. This setup allows for fine-grained control over connection handling and message sizes. ```javascript var wsServer = new WebSocketServer({ httpServer: httpsServer, // Use HTTPS autoAcceptConnections: false, maxReceivedFrameSize: 128 * 1024, maxReceivedMessageSize: 2 * 1024 * 1024, keepalive: true, keepaliveInterval: 30000, disableNagleAlgorithm: true }); ``` -------------------------------- ### Recommended WebSocket Server Initialization Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/Deprecation.md Demonstrates the current recommended way to initialize a WebSocket server, avoiding any potentially deprecated APIs. ```javascript var WebSocketServer = require('websocket').server; var server = new WebSocketServer({ httpServer: httpServer }); ``` -------------------------------- ### Instantiate WebSocketServer with Configuration Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Use this to create a new WebSocketServer instance, passing a configuration object to customize its behavior. ```javascript var server = new WebSocketServer(config); ``` -------------------------------- ### Instantiate W3CWebSocket and Check Ready State Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/W3CWebSocket.md Demonstrates how to create a new W3CWebSocket instance and access its ready state constants for checking the connection status. ```javascript var ws = new W3CWebSocket('ws://localhost/'); console.log(ws.OPEN); // 1 console.log(W3CWebSocket.OPEN); // 1 if (ws.readyState === ws.OPEN) { ws.send('message'); } ``` -------------------------------- ### W3CWebSocket Constructor Usage Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Illustrates the parameters for constructing a W3CWebSocket instance, including URL, protocols, origin, headers, request options, and client configuration. ```javascript var ws = new W3CWebSocket(url, protocols, origin, headers, requestOptions, clientConfig); ``` -------------------------------- ### Get WebSocket URL Source: https://github.com/theturtle32/websocket-node/blob/master/test/scripts/libwebsockets-test.html Determines the appropriate WebSocket URL based on the current page's protocol (ws:// or wss://). ```javascript function get_appropriate_ws_url() { var pcol; var u = document.URL; /* * We open the websocket encrypted if this page came on an * https:// url itself, otherwise unencrypted */ if (u.substring(0, 5) == "https") { pcol = "wss://"; u = u.substr(8); } else { pcol = "ws://"; if (u.substring(0, 4) == "http") u = u.substr(7); } u = u.split('/'); return pcol + u[0]; } ``` -------------------------------- ### Instantiate W3CWebSocket in Node.js Source: https://github.com/theturtle32/websocket-node/blob/master/docs/W3CWebSocket.md Demonstrates how to require and instantiate the W3CWebSocket class in a Node.js environment. It shows the constructor usage with URL, protocols, and origin, and highlights its equivalence to the browser's native WebSocket when browserified. ```javascript var WS = require('websocket').w3cwebsocket; WS === window.WebSocket // => true when in the browser var ws = new WS('ws://example.com/resource', 'foo', 'http://example.com'); // - In Node it creates an instance of websocket.W3CWebSocket. // - In the browser it creates an instance of window.WebSocket (third parameter // is ignored by the native WebSocket constructor). ws.onopen = function() { console.log('ws open'); }; // etc. ``` -------------------------------- ### Connect WebSocket using a Proxy Server Source: https://github.com/theturtle32/websocket-node/blob/master/docs/WebSocketClient.md Connects to a WebSocket server through an HTTP proxy using the node-tunnel library. Ensure the 'tunnel' and 'websocket' modules are installed. ```javascript var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); var tunnel = require('tunnel'); var tunnelingAgent = tunnel.httpOverHttp({ proxy: { host: 'proxy.host.com', port: 8080 } }); var requestOptions = { agent: tunnelingAgent }; client.connect('ws://echo.websocket.org/', null, null, null, requestOptions); ``` -------------------------------- ### Instantiate WebSocketServer Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketServer.md Create a new WebSocketServer instance with a configuration object. The config object specifies various server settings. ```javascript new WebSocketServer(config) ``` -------------------------------- ### Constructor Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/W3CWebSocket.md Initializes a new W3CWebSocket instance. It establishes a connection to the specified WebSocket URL with optional protocols, origin, headers, and request options. ```APIDOC ## Constructor ### Description Initializes a new W3CWebSocket instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | url | string | yes | WebSocket URL (ws:// or wss://) | | protocols | string \| string[] | no | Subprotocol(s) to request | | origin | string | no | Origin header value | | headers | object | no | Additional HTTP headers | | requestOptions | object | no | Extra http/https.request options | | clientConfig | object | no | WebSocketClient configuration | ### Request Example ```javascript new W3CWebSocket('ws://localhost:8080', ['chat', 'chatv2'], 'http://example.com', { 'X-Custom-Header': 'value' }, { timeout: 5000 }, { assembleFragments: true }); ``` ### Response #### Success Response None (constructor does not return a value) #### Response Example None ``` -------------------------------- ### Automatic Message Fragmentation Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketFrame.md Long messages are automatically split into multiple WebSocket frames based on the fragmentationThreshold. This example illustrates how a large message is broken down into frames. ```javascript // Server configured with fragmentationThreshold: 16KB var longMessage = Buffer.alloc(100000, 'x'); connection.sendBytes(longMessage); // Generates 7 frames: // Frame 1: opcode=0x02 (BINARY), fin=0, length=16384 // Frame 2-6: opcode=0x00 (CONTINUATION), fin=0, length=16384 // Frame 7: opcode=0x00 (CONTINUATION), fin=1, length=3616 ``` -------------------------------- ### Instantiate WebSocketClient with Configuration Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Use this to create a new WebSocketClient instance, passing a configuration object to customize its behavior. ```javascript var client = new WebSocketClient(config); ``` -------------------------------- ### Connect to WebSocket Server Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketClient.md Initiates a WebSocket connection. Use this method to establish a connection to a server, specifying the URL, optional subprotocols, origin, and headers. The client emits 'connect' on success or 'connectFailed' on failure. ```javascript var client = new WebSocketClient(); client.on('connect', function(connection) { console.log('Connected!'); }); client.on('connectFailed', function(error) { console.error('Connect failed:', error); }); client.connect('ws://example.com/chat', 'chat-protocol', 'http://example.com'); ``` -------------------------------- ### Configure WebSocket Server Options Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Set up essential WebSocket server options for production, including message size limits, fragmentation, keep-alive settings, and security configurations. Ensure 'autoAcceptConnections' is false for manual validation. ```javascript var wsServer = new WebSocketServer({ httpServer: httpsServer, // Use HTTPS // Reasonable message limits maxReceivedFrameSize: 128 * 1024, maxReceivedMessageSize: 2 * 1024 * 1024, // Outgoing message handling fragmentOutgoingMessages: true, fragmentationThreshold: 32 * 1024, // Connection health keepalive: true, keepaliveInterval: 30000, dropConnectionOnKeepaliveTimeout: true, keepaliveGracePeriod: 10000, useNativeKeepalive: false, // More responsive // Message assembly assembleFragments: true, // Security autoAcceptConnections: false, ignoreXForwardedFor: false, // Check if behind proxy parseCookies: true, parseExtensions: false, // Not supported // Performance disableNagleAlgorithm: true, // Cleanup closeTimeout: 5000 }); ``` -------------------------------- ### Monitoring Raw WebSocket Frame Exchange Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketFrame.md A low-level example demonstrating how to monitor raw frame exchanges on a WebSocket server. It logs details of received frames, including opcode, FIN bit, length, and payload content for text and binary frames. ```javascript var WebSocketFrame = require('websocket').frame; var WebSocketConnection = require('websocket').connection; // Monitor raw frame exchange wsServer.on('request', function(request) { var connection = request.accept(); connection.on('frame', function(frame) { console.log('Received frame:'); console.log(' Opcode: 0x' + frame.opcode.toString(16)); console.log(' FIN:', frame.fin); console.log(' Length:', frame.length); if (frame.opcode === 0x01) { // TEXT frame var text = frame.binaryPayload.toString('utf8'); console.log(' Text:', text); } else if (frame.opcode === 0x02) { // BINARY frame console.log(' Binary:', frame.binaryPayload); } }); }); ``` -------------------------------- ### WebSocketRouter Constructor Usage Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Shows how to instantiate a WebSocketRouter, optionally passing a configuration object. ```javascript var router = new WebSocketRouter(config); ``` -------------------------------- ### Create WebSocket Server Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/README.md Sets up a basic WebSocket server that listens for incoming connections and messages on port 8080. ```javascript var WebSocketServer = require('websocket').server; var http = require('http'); var server = http.createServer(); var wsServer = new WebSocketServer({ httpServer: server }); wsServer.on('request', function(request) { var connection = request.accept(); connection.on('message', function(msg) { console.log(msg.utf8Data); }); }); server.listen(8080); ``` -------------------------------- ### Handle Client Upgrade Requests Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketServer.md Emitted when a client sends an upgrade request. Use the request object to inspect details and accept or reject the connection. This snippet shows how to accept a connection with a specific protocol. ```javascript server.on('request', function(request) { console.log('Origin:', request.origin); console.log('Requested protocols:', request.requestedProtocols); var connection = request.accept('echo-protocol', request.origin); console.log('Connection accepted'); }); ``` -------------------------------- ### Handle Connection Open Event Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/W3CWebSocket.md Sets up an event handler for the 'onopen' event to execute code when the WebSocket connection is successfully established. This is a common place to send initial messages. ```javascript var ws = new W3CWebSocket('ws://localhost/'); ws.onopen = function() { console.log('Connected'); ws.send('Hello!'); }; ``` -------------------------------- ### Create WebSocket Client Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/README.md Establishes a WebSocket client connection to a specified server, handling connection events and incoming messages. ```javascript var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); client.on('connect', function(connection) { connection.on('message', function(msg) { console.log(msg.utf8Data); }); }); client.on('connectFailed', function(error) { console.error('Failed:', error); }); client.connect('ws://localhost:8080/'); ``` -------------------------------- ### Router: Missing Parameters Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/errors.md Provide all required parameters (path and callback) when mounting a router handler. ```javascript router.mount(); // Missing everything router.mount('/path'); // Missing callback ``` ```javascript router.mount( '/path', // Path 'protocol', // Protocol (optional) function(request) { // Callback (required) request.accept(); } ); ``` -------------------------------- ### Ready States (W3CWebSocket) Enumeration Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/types.md Details the ready states for a W3CWebSocket, including CONNECTING, OPEN, CLOSING, and CLOSED, represented by numerical values. ```APIDOC ### Ready States (W3CWebSocket) Used in `ws.readyState`: ```javascript const CONNECTING = 0; // Connection in progress const OPEN = 1; // Connection established const CLOSING = 2; // Close handshake in progress const CLOSED = 3; // Fully closed ``` ``` -------------------------------- ### WebSocketServer Constructor Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketServer.md Initializes a new WebSocketServer instance. The constructor accepts a configuration object to customize server behavior, including attachment to an HTTP server, message size limits, keepalive settings, and more. ```APIDOC ## new WebSocketServer(config) ### Description Initializes a new WebSocketServer instance with the provided configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (object) - Required - Configuration object for server settings. * **httpServer** (http.Server | https.Server | Array) - Required - HTTP/HTTPS server instance(s) to attach to. * **maxReceivedFrameSize** (number) - Optional - Maximum size of a received WebSocket frame. Defaults to 64 KiB. * **maxReceivedMessageSize** (number) - Optional - Maximum size of an aggregated received message. Defaults to 1 MiB. * **fragmentOutgoingMessages** (boolean) - Optional - Whether to split outgoing messages into fragments. Defaults to true. * **fragmentationThreshold** (number) - Optional - Size threshold for fragmenting outgoing messages. Defaults to 16 KiB. * **keepalive** (boolean) - Optional - Whether to send automatic keepalive ping frames. Defaults to true. * **keepaliveInterval** (number) - Optional - Milliseconds between keepalive ping frames. Defaults to 20000. * **dropConnectionOnKeepaliveTimeout** (boolean) - Optional - Drop connections that don't respond to keepalive pings. Defaults to true. * **keepaliveGracePeriod** (number) - Optional - Milliseconds to wait for pong response after ping. Defaults to 10000. * **useNativeKeepalive** (boolean) - Optional - Use TCP-level keepalive instead of WebSocket ping/pong. Defaults to false. * **assembleFragments** (boolean) - Optional - Automatically assemble fragmented messages. Defaults to true. * **autoAcceptConnections** (boolean) - Optional - Auto-accept all connections regardless of origin/protocol. Defaults to false. * **ignoreXForwardedFor** (boolean) - Optional - Whether to ignore X-Forwarded-For header. Defaults to false. * **parseCookies** (boolean) - Optional - Parse incoming cookie headers. Defaults to true. * **parseExtensions** (boolean) - Optional - Parse sec-websocket-extensions headers. Defaults to true. * **disableNagleAlgorithm** (boolean) - Optional - Disable Nagle's algorithm for lower latency. Defaults to true. * **closeTimeout** (number) - Optional - Milliseconds to wait for close handshake acknowledgment. Defaults to 5000. ### Request Example ```javascript const server = new WebSocketServer({ httpServer: myHttpServer, maxReceivedMessageSize: 1024 * 1024, // 1 MiB keepalive: true }); ``` ### Response None ``` -------------------------------- ### Configure WebSocketClient Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/types.md Instantiate a WebSocketClient with a configuration object. Options control message size limits, fragmentation, protocol version, and TLS settings. ```javascript var config = { maxReceivedFrameSize: 0x100000, maxReceivedMessageSize: 0x800000, fragmentOutgoingMessages: true, fragmentationThreshold: 0x4000, webSocketVersion: 13, assembleFragments: true, disableNagleAlgorithm: true, closeTimeout: 5000, tlsOptions: {} }; var client = new WebSocketClient(config); ``` -------------------------------- ### Attach WebSocket Server After Construction Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Instantiate the WebSocket server without an HTTP server and mount it later using the `mount` method. The server can be remounted on different HTTP servers. ```javascript var wsServer = new WebSocketServer(); wsServer.mount({ httpServer: httpServer }); wsServer.mount({ httpServer: anotherServer }); // Can mount again ``` -------------------------------- ### Configure for Mobile (Bandwidth-Constrained) Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/configuration.md Optimize for mobile devices with bandwidth constraints by using conservative frame/fragmentation thresholds, longer keepalive intervals, and enabling native keepalive. ```javascript var wsServer = new WebSocketServer({ maxReceivedFrameSize: 32 * 1024, fragmentOutgoingMessages: true, fragmentationThreshold: 32 * 1024, // Conservative assembleFragments: true, keepalive: true, keepaliveInterval: 60000, useNativeKeepalive: true, // Save WebSocket overhead disableNagleAlgorithm: false // Allow batching }); ``` -------------------------------- ### Configure W3CWebSocket Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/types.md Instantiate a W3CWebSocket with a configuration object. Similar to WebSocketClient, but assembleFragments is always true to comply with the W3C specification. ```javascript var config = { maxReceivedFrameSize: 0x100000, maxReceivedMessageSize: 0x800000, // ... other client options // assembleFragments is forced to true per W3C spec }; var ws = new W3CWebSocket(url, protocols, origin, headers, requestOptions, config); ``` -------------------------------- ### Configure WebSocket Server for Development Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/README.md Initializes a WebSocket server for development, disabling automatic connection acceptance to allow for request validation. ```javascript var wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false // Validate requests }); ``` -------------------------------- ### Request: Missing Headers Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/errors.md Clients must provide Host, Sec-WebSocket-Key, and Sec-WebSocket-Version headers. Client libraries typically generate these. ```text Error: Client must provide a Host header. Error: Client must provide a value for Sec-WebSocket-Key. Error: Client must provide a value for Sec-WebSocket-Version. ``` -------------------------------- ### Build Autobahn Test Suite Docker Image Source: https://github.com/theturtle32/websocket-node/blob/master/test/autobahn/README.md Builds the Autobahn Test Suite Docker image using specific build arguments for version and date. ```bash docker build \ --build-arg AUTOBAHN_TESTSUITE_VCS_REF=c3655a9 \ --build-arg BUILD_DATE=2020-08-28 \ --build-arg AUTOBAHN_TESTSUITE_VERSION=0.8.1 \ -t crossbario/autobahn-testsuite:latest \ . ``` -------------------------------- ### Basic WebSocket Client Connection Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketClient.md Establishes a WebSocket connection, handles connection events (connectFailed, connect, error, close), and processes incoming UTF-8 messages. Sends a test message upon successful connection. ```javascript var WebSocketClient = require('websocket').client; var client = new WebSocketClient({ webSocketVersion: 13, assembleFragments: true }); client.on('connectFailed', function(error) { console.log('Connect Error: ' + error.toString()); process.exit(1); }); client.on('connect', function(connection) { console.log('WebSocket client connected'); connection.on('error', function(error) { console.log('Connection Error: ' + error.toString()); }); connection.on('close', function() { console.log('Connection Closed'); }); connection.on('message', function(message) { if (message.type === 'utf8') { console.log("Received: '" + message.utf8Data + "'"); } }); // Send a test message connection.sendUTF('Hello Server'); }); // Connect with custom headers and TLS options client.connect( 'wss://example.com/ws', 'my-protocol', 'https://example.com', { 'X-Custom-Header': 'value' }, { rejectUnauthorized: false // For self-signed certs (not recommended for production) } ); ``` -------------------------------- ### connect Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketClient.md Initiates a WebSocket connection to the specified URL. It supports both ws:// and wss:// protocols and allows for custom subprotocols, origin, headers, and request options. ```APIDOC ## connect(requestUrl, protocols, origin, headers, extraRequestOptions) ### Description Initiate a WebSocket connection to the specified URL. Supports both ws:// (port 80 default) and wss:// (port 443 default) protocols. For TLS connections, `tlsOptions` from config are passed to https.request. Emits 'connect' event on successful connection, 'connectFailed' on failure, and 'httpResponse' if server responds with non-101 status. ### Method connect ### Endpoint N/A (Method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **requestUrl** (string | URL) - Required - WebSocket URL (ws:// or wss://) * **protocols** (string | string[]) - Optional - Subprotocol(s) to request (Default: []) * **origin** (string) - Optional - Origin header value * **headers** (object) - Optional - Additional HTTP headers (Default: {}) * **extraRequestOptions** (object) - Optional - Extra options for http/https.request (Default: {}) ### Returns undefined ### Throws * Error: If URL doesn't include protocol * Error: If URL doesn't include hostname * Error: If protocol contains invalid characters * Error: If webSocketVersion is not 8 or 13 ``` -------------------------------- ### Handle Incoming Messages (Text and Binary) Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/W3CWebSocket.md Sets up the 'onmessage' event handler to process incoming data, distinguishing between text and binary messages. ```javascript ws.onmessage = function(event) { if (typeof event.data === 'string') { console.log('Text:', event.data); } else { console.log('Binary:', event.data); // ArrayBuffer or Buffer } }; ``` -------------------------------- ### mount(config) Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/WebSocketServer.md Mounts the WebSocket server to an HTTP server instance, enabling it to handle WebSocket upgrade requests. This method requires a configuration object that includes the HTTP server instance. ```APIDOC ## server.mount(config) ### Description Mount the server to an HTTP server with the provided configuration. ### Method Not applicable (Instance method) ### Endpoint Not applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (object) - Required - Configuration object (see constructor config above). ### Request Example ```javascript server.mount({ httpServer: myHttpServer, keepalive: true, autoAcceptConnections: false }); ``` ### Response #### Success Response (200) None #### Response Example None ### Throws * **Error** - If `httpServer` is not specified in config. ``` -------------------------------- ### Configure WebSocket Version Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/errors.md Specify a valid webSocketVersion (8 or 13) in the client configuration. Unsupported versions will result in an error. ```javascript var client = new WebSocketClient({ webSocketVersion: 11 // Must be 8 or 13 }); ``` ```javascript var client = new WebSocketClient({ webSocketVersion: 13 // RFC 6455 }); ``` -------------------------------- ### W3CWebSocket vs. WebSocketClient Source: https://github.com/theturtle32/websocket-node/blob/master/_autodocs/api-reference/W3CWebSocket.md Illustrates the difference between using the Node.js-specific WebSocketClient and the browser-compatible W3CWebSocket API. Shows equivalent connection and message handling patterns. ```javascript // Using WebSocketClient (node-specific) var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); client.on('connect', function(connection) { connection.sendUTF('message'); connection.on('message', function(msg) { console.log(msg.utf8Data); }); }); client.connect('ws://localhost/'); // Using W3CWebSocket (browser-compatible) var W3CWebSocket = require('websocket').w3cwebsocket; var ws = new W3CWebSocket('ws://localhost/'); ws.send('message'); ws.onmessage = function(event) { console.log(event.data); }; ```