Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455
npx @tessl/cli install tessl/npm-websocket@1.0.0WebSocket 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.
npm install websocketconst 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;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);
}
});
});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/');WebSocket is built around several key components:
WebSocketServer handles HTTP upgrade requests and manages connectionsWebSocketClient creates outbound connections with full configuration controlWebSocketConnection provides bidirectional communication with event-driven message handlingWebSocketRequest manages the handshake process with accept/reject capabilitiesWebSocketRouter enables path and protocol-based request routingW3CWebSocket provides standard WebSocket API compatibilityWebSocketFrame handles low-level protocol frame parsing and constructionComplete 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;
}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;
}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;
}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;
}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;
}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
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;
}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;
}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
};