or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client.mdconnection.mdframe.mdindex.mdrouter-request.mdserver.mdutilities.md
tile.json

tessl/npm-websocket

Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/websocket@1.0.x

To install, run

npx @tessl/cli install tessl/npm-websocket@1.0.0

index.mddocs/

WebSocket

WebSocket is a comprehensive Node.js library that implements the WebSocket protocol as specified in RFC 6455. It provides both client and server functionality with support for multiple WebSocket protocol versions (8 and 13), featuring extensive configuration options, automatic message fragmentation, keepalive functionality, and W3C-compliant APIs.

Package Information

  • Package Name: websocket
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install websocket

Core Imports

const WebSocket = require('websocket');

// Access individual components
const server = WebSocket.server;
const client = WebSocket.client;
const router = WebSocket.router;
const frame = WebSocket.frame;
const connection = WebSocket.connection;
const request = WebSocket.request;
const w3cwebsocket = WebSocket.w3cwebsocket;
const version = WebSocket.version;

For browser usage:

const { w3cwebsocket: W3CWebSocket, version } = require('websocket/lib/browser');

// Use native WebSocket if available, fallback to library implementation
const WebSocketClass = W3CWebSocket || WebSocket;

Basic Usage

Quick Server Setup

const WebSocket = require('websocket');
const http = require('http');

// Create HTTP server
const server = http.createServer();
server.listen(8080);

// Create WebSocket server
const wsServer = new WebSocket.server({
    httpServer: server,
    autoAcceptConnections: false
});

wsServer.on('request', function(request) {
    const connection = request.accept(null, request.origin);
    
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received: ' + message.utf8Data);
            connection.sendUTF('Echo: ' + message.utf8Data);
        }
    });
});

Quick Client Setup

const WebSocket = require('websocket');

const client = new WebSocket.client();

client.on('connect', function(connection) {
    connection.sendUTF('Hello Server!');
    
    connection.on('message', function(message) {
        console.log('Received: ' + message.utf8Data);
    });
});

client.connect('ws://localhost:8080/');

Architecture

WebSocket is built around several key components:

  • Server Infrastructure: WebSocketServer handles HTTP upgrade requests and manages connections
  • Client Infrastructure: WebSocketClient creates outbound connections with full configuration control
  • Connection Management: WebSocketConnection provides bidirectional communication with event-driven message handling
  • Request Processing: WebSocketRequest manages the handshake process with accept/reject capabilities
  • Routing System: WebSocketRouter enables path and protocol-based request routing
  • W3C Compliance: W3CWebSocket provides standard WebSocket API compatibility
  • Frame Processing: WebSocketFrame handles low-level protocol frame parsing and construction

Capabilities

Server-Side WebSocket Handling

Complete server-side WebSocket implementation with HTTP server integration, request routing, and connection management.

// Main server class
class WebSocketServer extends EventEmitter {
    constructor(config?: ServerConfig);
    mount(config: ServerConfig): void;
    unmount(): void;
    closeAllConnections(): void;
    broadcast(data: Buffer | string): void;
    shutDown(): void;
}

// Request handling
class WebSocketRequest extends EventEmitter {
    accept(acceptedProtocol?: string, allowedOrigin?: string, cookies?: Cookie[]): WebSocketConnection;
    reject(status?: number, reason?: string, extraHeaders?: object): void;
}

// Routing system
class WebSocketRouter extends EventEmitter {
    mount(path: string | RegExp, protocol: string, callback: (request: WebSocketRouterRequest) => void): void;
    unmount(path: string | RegExp, protocol: string): void;
}

Server-Side Operations

Client-Side WebSocket Connections

Outbound WebSocket client with full protocol support and W3C-compliant API.

// Native WebSocket client
class WebSocketClient extends EventEmitter {
    constructor(config?: ClientConfig);
    connect(requestUrl: string, protocols?: string | string[], origin?: string, headers?: object, extraRequestOptions?: object): void;
    abort(): void;
}

// W3C-compliant WebSocket API
class W3CWebSocket {
    constructor(url: string, protocols?: string | string[], origin?: string, headers?: object, requestOptions?: object, clientConfig?: object);
    send(data: string | Buffer | ArrayBuffer): void;
    close(code?: number, reason?: string): void;
    readonly readyState: number;
    readonly protocol: string;
}

Client-Side Operations

Bidirectional Connection Communication

Active WebSocket connection handling for both client and server sides with comprehensive message and event support.

class WebSocketConnection extends EventEmitter {
    send(data: Buffer | string, callback?: (error?: Error) => void): void;
    sendUTF(data: string, callback?: (error?: Error) => void): void;
    sendBytes(data: Buffer, callback?: (error?: Error) => void): void;
    ping(data?: Buffer): void;
    close(reasonCode?: number, description?: string): void;
    drop(reasonCode?: number, description?: string, skipCloseFrame?: boolean): void;
    
    readonly connected: boolean;
    readonly state: string;
    readonly protocol: string;
    readonly remoteAddress: string;
}

Connection Management

Low-Level Frame Processing

Direct WebSocket frame parsing and construction for advanced use cases.

class WebSocketFrame {
    constructor(maskBytes?: Buffer, frameHeader?: object, config?: object);
    addData(buffer: Buffer): boolean;
    toBuffer(nullMask?: boolean): Buffer;
    
    fin: boolean;
    opcode: number;
    length: number;
    binaryPayload: Buffer;
}

Frame-Level Operations

Router Request Processing

Simplified request handling within router context for path and protocol-based routing.

class WebSocketRouterRequest extends EventEmitter {
    accept(origin?: string, cookies?: Cookie[]): WebSocketConnection;
    reject(status?: number, reason?: string, extraHeaders?: object): void;
    
    readonly webSocketRequest: WebSocketRequest;
    readonly protocol: string;
    readonly origin: string;
    readonly resource: string;
}

Router Request Handling

Utilities and Version Information

Library version information, deprecation handling, and utility functions.

// Version information
const version: string;

// Deprecation management
class Deprecation {
    static disableWarnings: boolean;
    static warn(deprecationName: string): void;
}

// Browser compatibility
interface BrowserExports {
    w3cwebsocket: typeof W3CWebSocket | null;
    version: string;
}

Utilities and Version Information

Types

Configuration Types

interface ServerConfig {
    httpServer: http.Server | https.Server | http.Server[];
    maxReceivedFrameSize?: number;
    maxReceivedMessageSize?: number;
    fragmentOutgoingMessages?: boolean;
    fragmentationThreshold?: number;
    keepalive?: boolean;
    keepaliveInterval?: number;
    dropConnectionOnKeepaliveTimeout?: boolean;
    keepaliveGracePeriod?: number;
    useNativeKeepalive?: boolean;
    assembleFragments?: boolean;
    autoAcceptConnections?: boolean;
    ignoreXForwardedFor?: boolean;
    parseCookies?: boolean;
    parseExtensions?: boolean;
    disableNagleAlgorithm?: boolean;
    closeTimeout?: number;
}

interface ClientConfig {
    maxReceivedFrameSize?: number;
    maxReceivedMessageSize?: number;
    fragmentOutgoingMessages?: boolean;
    fragmentationThreshold?: number;
    webSocketVersion?: number;
    assembleFragments?: boolean;
    disableNagleAlgorithm?: boolean;
    closeTimeout?: number;
    tlsOptions?: object;
}

Message and Event Types

interface WebSocketMessage {
    type: 'utf8' | 'binary';
    utf8Data?: string;
    binaryData?: Buffer;
}

interface Cookie {
    name: string;
    value: string;
    path?: string;
    domain?: string;
    expires?: Date;
    maxage?: number;
    secure?: boolean;
    httponly?: boolean;
}

Close Reason Constants

const CLOSE_REASONS = {
    NORMAL: 1000,
    GOING_AWAY: 1001,
    PROTOCOL_ERROR: 1002,
    UNPROCESSABLE_INPUT: 1003,
    RESERVED: 1004,
    NOT_PROVIDED: 1005,
    ABNORMAL: 1006,
    INVALID_DATA: 1007,
    POLICY_VIOLATION: 1008,
    MESSAGE_TOO_BIG: 1009,
    EXTENSION_REQUIRED: 1010,
    INTERNAL_SERVER_ERROR: 1011,
    TLS_HANDSHAKE_FAILED: 1015
};