CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-faye-websocket

Standards-compliant WebSocket server and client implementation for Node.js with EventSource support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

websocket-server.mddocs/

WebSocket Server

Server-side WebSocket implementation that handles HTTP upgrade requests and manages WebSocket connections with full protocol compliance.

Capabilities

WebSocket Constructor

Creates a new server-side WebSocket connection from an HTTP upgrade request.

/**
 * Creates a server-side WebSocket connection
 * @param {Object} request - HTTP request object
 * @param {Object} socket - Network socket
 * @param {Buffer} body - Request body
 * @param {Array} [protocols] - Supported protocol strings
 * @param {Object} [options] - Configuration options
 */
const WebSocket = require('faye-websocket');
const ws = new WebSocket(request, socket, body, protocols, options);

Usage Example:

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

const server = http.createServer();

server.on('upgrade', function(request, socket, body) {
  if (WebSocket.isWebSocket(request)) {
    const ws = new WebSocket(request, socket, body, ['chat', 'echo']);
    
    ws.on('open', function(event) {
      console.log('WebSocket connection opened');
    });
    
    ws.on('message', function(event) {
      // Echo the message back
      ws.send(event.data);
    });
    
    ws.on('close', function(event) {
      console.log('Connection closed:', event.code, event.reason);
    });
  }
});

Static Methods

isWebSocket

Checks if an HTTP request is a WebSocket upgrade request.

/**
 * Checks if an HTTP request is a WebSocket upgrade request
 * @param {Object} request - HTTP request object
 * @returns {boolean} True if request is WebSocket upgrade
 */
WebSocket.isWebSocket(request);

validateOptions

Validates WebSocket options against allowed keys.

/**
 * Validates WebSocket options against allowed keys
 * @param {Object} options - Options object to validate
 * @param {Array} validKeys - Array of valid option key names
 * @throws {Error} If invalid options are provided
 */
WebSocket.validateOptions(options, validKeys);

Instance Properties

Connection State

ws.readyState;     // Number - Connection state (0-3)
ws.protocol;       // String - Selected subprotocol
ws.url;           // String - WebSocket URL
ws.version;       // String - WebSocket protocol version
ws.bufferedAmount; // Number - Bytes queued for transmission

Stream Properties

ws.readable;  // Boolean - Stream readable state
ws.writable;  // Boolean - Stream writable state

Instance Methods

send

Sends a message to the connected client.

/**
 * Sends a message to the connected client
 * @param {string|Buffer} data - Message data
 * @returns {boolean} True if message was queued successfully
 */
ws.send(data);

ping

Sends a ping frame to the client.

/**
 * Sends a ping frame to the client
 * @param {string} [message] - Optional ping message
 * @param {Function} [callback] - Called when pong is received
 * @returns {boolean} True if ping was sent, false if unsupported
 */
ws.ping(message, callback);

Usage Example:

ws.ping('keepalive', function() {
  console.log('Pong received');
});

close

Closes the WebSocket connection.

/**
 * Closes the WebSocket connection
 * @param {number} [code=1000] - Close status code
 * @param {string} [reason=''] - Close reason
 * @throws {Error} If code is invalid (not 1000 or 3000-4999)
 */
ws.close(code, reason);

Stream Methods

// Stream interface methods
ws.write(data);    // Alias for send()
ws.end(data);      // Send final message and close
ws.pause();        // Pause message processing
ws.resume();       // Resume message processing

Events

open

Fired when the WebSocket connection is established.

ws.on('open', function(event) {
  // Connection is ready for communication
});

message

Fired when a message is received from the client.

ws.on('message', function(event) {
  // event.data contains the message (String or Buffer)
  console.log('Received:', event.data);
});

error

Fired when a protocol error occurs.

ws.on('error', function(event) {
  // event.message contains error description
  console.log('Error:', event.message);
});

close

Fired when the connection is closed.

ws.on('close', function(event) {
  // event.code and event.reason contain close details
  console.log('Closed:', event.code, event.reason);
});

Event Handler Properties

Alternative to using on() for event handling:

ws.onopen = function(event) { /* handle open */ };
ws.onmessage = function(event) { /* handle message */ };
ws.onerror = function(event) { /* handle error */ };
ws.onclose = function(event) { /* handle close */ };

Configuration Options

// Available options for WebSocket constructor
{
  extensions: Array,    // WebSocket extensions to negotiate
  headers: Object,      // Custom HTTP headers for handshake
  maxLength: number,    // Maximum frame size (default: 67108863)
  ping: number         // Ping interval in seconds
}

Usage Example:

const ws = new WebSocket(request, socket, body, [], {
  headers: { 'X-Custom-Header': 'value' },
  maxLength: 1024 * 1024, // 1MB max frame size
  ping: 30 // Ping every 30 seconds
});

Protocol Negotiation

// Server specifies supported protocols
const ws = new WebSocket(request, socket, body, ['chat', 'echo', 'binary']);

// After connection, check negotiated protocol
console.log('Selected protocol:', ws.protocol);

Extension Support

// Add WebSocket extensions
const deflate = require('permessage-deflate');
const ws = new WebSocket(request, socket, body, [], {
  extensions: [deflate]
});

Error Handling

ws.on('error', function(event) {
  console.log('WebSocket error:', event.message);
  // Errors are informational - no recovery needed
});

// Handle close with error codes
ws.on('close', function(event) {
  if (event.code !== 1000) {
    console.log('Abnormal close:', event.code, event.reason);
  }
});

docs

eventsource.md

index.md

websocket-client.md

websocket-server.md

tile.json