Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455
—
Client-side WebSocket implementation providing outbound connection capabilities with both native API and W3C-compliant interfaces for connecting to WebSocket servers.
Native WebSocket client for creating outbound connections with full configuration control.
/**
* WebSocket client for creating outbound connections
* @param config - Client configuration options
*/
class WebSocketClient extends EventEmitter {
constructor(config?: ClientConfig);
/**
* Connect to WebSocket server
* @param requestUrl - WebSocket URL (ws:// or wss://)
* @param protocols - Array of protocols or single protocol string
* @param origin - Origin header value
* @param headers - Additional HTTP headers object
* @param extraRequestOptions - Additional options for HTTP request
*/
connect(requestUrl: string, protocols?: string | string[], origin?: string, headers?: object, extraRequestOptions?: object): void;
/** Abort connection attempt */
abort(): void;
/** Client configuration object */
readonly config: ClientConfig;
/** Parsed URL object of connection target */
readonly url: URL;
/** Array of requested protocols */
readonly protocols: string[];
/** Origin header value */
readonly origin: string;
/** Negotiated protocol (after successful connection) */
readonly protocol: string;
/** Whether connection uses TLS/SSL (wss://) */
readonly secure: boolean;
}Configuration:
interface ClientConfig {
/** Maximum frame size in bytes (default: 1MiB) */
maxReceivedFrameSize?: number;
/** Maximum message size in bytes (default: 8MiB) */
maxReceivedMessageSize?: number;
/** Whether to fragment outgoing messages (default: true) */
fragmentOutgoingMessages?: boolean;
/** Fragment messages larger than this size (default: 16KiB) */
fragmentationThreshold?: number;
/** WebSocket protocol version 8 or 13 (default: 13) */
webSocketVersion?: number;
/** Assemble fragmented messages (default: true) */
assembleFragments?: boolean;
/** Disable Nagle algorithm (default: true) */
disableNagleAlgorithm?: boolean;
/** Close frame timeout in milliseconds (default: 5000) */
closeTimeout?: number;
/** TLS connection options object */
tlsOptions?: object;
}Events:
'connect' - (WebSocketConnection) - Connection successful'connectFailed' - (error) - Connection failed'httpResponse' - (response, client) - Non-101 HTTP response receivedUsage Example:
const WebSocket = require('websocket');
const client = new WebSocket.client({
maxReceivedFrameSize: 1024 * 1024,
maxReceivedMessageSize: 8 * 1024 * 1024,
webSocketVersion: 13,
tlsOptions: {
rejectUnauthorized: false // For self-signed certificates
}
});
client.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', function(connection) {
console.log('WebSocket Client Connected');
console.log('Connected Protocol: ' + connection.protocol);
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 message
if (connection.connected) {
connection.sendUTF('Hello Server!');
}
});
// Connect to server
client.connect('ws://localhost:8080/', ['echo-protocol'], 'http://localhost', {
'User-Agent': 'My WebSocket Client'
});W3C-compliant WebSocket API implementation providing standard browser-like interface.
/**
* W3C-compliant WebSocket API implementation
* @param url - WebSocket URL (ws:// or wss://)
* @param protocols - Array of protocols or single protocol string
* @param origin - Origin header value
* @param headers - Additional HTTP headers object
* @param requestOptions - Additional request options
* @param clientConfig - WebSocketClient configuration
*/
class W3CWebSocket {
constructor(url: string, protocols?: string | string[], origin?: string, headers?: object, requestOptions?: object, clientConfig?: ClientConfig);
/**
* Send text or binary data
* @param data - String, Buffer, or ArrayBuffer to send
*/
send(data: string | Buffer | ArrayBuffer): void;
/**
* Close connection
* @param code - Close status code (default: 1000)
* @param reason - Close reason string
*/
close(code?: number, reason?: string): void;
/**
* Add event listener
* @param type - Event type ('open', 'message', 'error', 'close')
* @param listener - Event handler function
*/
addEventListener(type: string, listener: (event: Event) => void): void;
/**
* Remove event listener
* @param type - Event type
* @param listener - Event handler function to remove
*/
removeEventListener(type: string, listener: (event: Event) => void): void;
/** WebSocket URL */
readonly url: string;
/** Connection state (0-3) */
readonly readyState: number;
/** Negotiated protocol */
readonly protocol: string;
/** Negotiated extensions (always empty string) */
readonly extensions: string;
/** Queued data amount in bytes (always 0) */
readonly bufferedAmount: number;
/** Binary data type ('arraybuffer') */
binaryType: string;
/** Open event handler */
onopen: ((event: Event) => void) | null;
/** Message event handler */
onmessage: ((event: MessageEvent) => void) | null;
/** Error event handler */
onerror: ((event: Event) => void) | null;
/** Close event handler */
onclose: ((event: CloseEvent) => void) | null;
}ReadyState Constants:
const ReadyState = {
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3
};
// Access via W3CWebSocket static properties
W3CWebSocket.CONNECTING = 0;
W3CWebSocket.OPEN = 1;
W3CWebSocket.CLOSING = 2;
W3CWebSocket.CLOSED = 3;Events (via addEventListener):
'open' - Connection opened'message' - Message received (event.data contains the data)'error' - Connection error'close' - Connection closed (event.code, event.reason, event.wasClean)Usage Example:
const { w3cwebsocket: W3CWebSocket } = require('websocket');
const 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('Connection Closed');
};
client.onmessage = function(e) {
if (typeof e.data === 'string') {
console.log("Received: '" + e.data + "'");
}
};
// Using addEventListener instead of direct assignment
client.addEventListener('open', function() {
console.log('Connection established via addEventListener');
});
client.addEventListener('message', function(e) {
console.log('Message via addEventListener: ' + e.data);
});Browser Compatibility:
For browser usage, import the browser-specific build:
// Browser environment
const { w3cwebsocket: W3CWebSocket } = require('websocket/lib/browser');
// If native WebSocket is available, W3CWebSocket will be null
// and you should use the native WebSocket instead
const WebSocketClass = W3CWebSocket || WebSocket;
const client = new WebSocketClass('ws://localhost:8080/');Custom Headers and Authentication:
const client = new WebSocket.client();
client.connect('wss://secure.example.com/websocket', ['custom-protocol'], 'https://example.com', {
'Authorization': 'Bearer ' + token,
'X-Custom-Header': 'custom-value'
}, {
// Extra request options
timeout: 10000,
agent: customHttpAgent
});TLS Configuration:
const client = new WebSocket.client({
tlsOptions: {
key: fs.readFileSync('client-key.pem'),
cert: fs.readFileSync('client-cert.pem'),
ca: fs.readFileSync('ca-cert.pem'),
rejectUnauthorized: true
}
});Protocol Version Selection:
// Force WebSocket protocol version 8
const client = new WebSocket.client({
webSocketVersion: 8
});
// Default is version 13 (latest)
const modernClient = new WebSocket.client({
webSocketVersion: 13
});interface MessageEvent {
data: string | ArrayBuffer;
origin: string;
lastEventId: string;
source: any;
ports: MessagePort[];
}
interface CloseEvent {
code: number;
reason: string;
wasClean: boolean;
}
interface Event {
type: string;
target: any;
currentTarget: any;
eventPhase: number;
bubbles: boolean;
cancelable: boolean;
timeStamp: number;
defaultPrevented: boolean;
}Install with Tessl CLI
npx tessl i tessl/npm-websocket