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-client.mddocs/

WebSocket Client

Client-side WebSocket implementation with support for secure connections, proxy servers, and complete WebSocket protocol compliance.

Capabilities

Client Constructor

Creates a new client-side WebSocket connection to a WebSocket server.

/**
 * Creates a client-side WebSocket connection
 * @param {string} url - WebSocket URL (ws:// or wss://)
 * @param {Array} [protocols] - Supported protocol strings
 * @param {Object} [options] - Configuration options
 */
const WebSocket = require('faye-websocket');
const ws = new WebSocket.Client(url, protocols, options);

Usage Example:

const WebSocket = require('faye-websocket');
const ws = new WebSocket.Client('wss://echo.websocket.org/', ['echo']);

ws.on('open', function(event) {
  console.log('Connected to server');
  ws.send('Hello, server!');
});

ws.on('message', function(event) {
  console.log('Received:', event.data);
});

ws.on('close', function(event) {
  console.log('Connection closed:', event.code, event.reason);
});

Client-Specific Properties

Handshake Information

After connection, the client exposes handshake response details:

ws.headers;    // Object - HTTP response headers from handshake
ws.statusCode; // Number - HTTP status code from handshake

Usage Example:

ws.on('open', function(event) {
  console.log('Status code:', ws.statusCode);
  console.log('Server headers:', ws.headers);
  console.log('Selected protocol:', ws.protocol);
});

Proxy Support

Connect through HTTP proxies with authentication and custom headers.

/**
 * Proxy configuration object
 * @param {string} origin - Proxy URL with optional auth
 * @param {Object} [headers] - Custom headers for proxy
 * @param {Object} [tls] - TLS settings for proxy connection
 */
const proxyOptions = {
  origin: 'http://username:password@proxy.example.com:8080',
  headers: { 'User-Agent': 'MyApp/1.0' },
  tls: { /* TLS options for proxy */ }
};

const ws = new WebSocket.Client('wss://example.com/', [], {
  proxy: proxyOptions
});

Complete Proxy Example:

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

const ws = new WebSocket.Client('wss://secure-api.example.com/', [], {
  proxy: {
    origin: 'https://corporate-proxy.company.com:8080',
    headers: {
      'User-Agent': 'MyApp/1.0',
      'X-Custom-Header': 'value'
    },
    tls: {
      cert: fs.readFileSync('client.crt'),
      key: fs.readFileSync('client.key')
    }
  }
});

TLS/SSL Configuration

Configure TLS settings for secure WebSocket connections.

/**
 * TLS configuration options
 * @param {string|Buffer} [ca] - Certificate authority
 * @param {string|Buffer} [cert] - Client certificate
 * @param {string|Buffer} [key] - Client private key
 * @param {string} [servername] - Server name for SNI
 */
const tlsOptions = {
  ca: fs.readFileSync('ca.pem'),
  cert: fs.readFileSync('client.crt'),
  key: fs.readFileSync('client.key'),
  servername: 'api.example.com'
};

const ws = new WebSocket.Client('wss://api.example.com/', [], {
  tls: tlsOptions
});

Network Configuration

Configure underlying network connection options.

/**
 * Network configuration options
 * @param {string} [host] - Target hostname
 * @param {number} [port] - Target port
 * @param {string} [localAddress] - Local interface to bind
 * @param {number} [localPort] - Local port to bind
 */
const netOptions = {
  localAddress: '192.168.1.100',
  timeout: 5000
};

const ws = new WebSocket.Client('ws://example.com/', [], {
  net: netOptions
});

Instance Methods

All WebSocket server methods are available on the client, plus client-specific functionality.

send

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

ping

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

close

/**
 * Closes the WebSocket connection
 * @param {number} [code=1000] - Close status code
 * @param {string} [reason=''] - Close reason
 */
ws.close(code, reason);

Events

The client supports all standard WebSocket events:

open

ws.on('open', function(event) {
  // Connection established - handshake complete
  console.log('Connected to:', ws.url);
  console.log('Protocol:', ws.protocol);
});

message

ws.on('message', function(event) {
  // event.data contains String or Buffer
  if (typeof event.data === 'string') {
    console.log('Text message:', event.data);
  } else {
    console.log('Binary message:', event.data.length, 'bytes');
  }
});

error

ws.on('error', function(event) {
  console.log('Connection error:', event.message);
});

close

ws.on('close', function(event) {
  console.log('Connection closed:', event.code, event.reason);
  // Common codes: 1000 (normal), 1006 (abnormal)
});

Configuration Options

// Client-specific configuration options
{
  // Connection options
  proxy: {
    origin: string,     // Proxy URL with optional auth
    headers: Object,    // Custom proxy headers
    tls: Object        // TLS settings for proxy
  },
  net: Object,         // Network connection options (passed to net.connect)
  tls: Object,         // TLS options (passed to tls.connect)
  ca: string|Buffer,   // Certificate authority (legacy shorthand)

  // WebSocket options (same as server)
  extensions: Array,   // WebSocket extensions
  headers: Object,     // Custom handshake headers
  maxLength: number,   // Max frame size
  ping: number        // Ping interval in seconds
}

Complete Client Example

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

const ws = new WebSocket.Client('wss://api.example.com/live', ['v1', 'v2'], {
  // Custom headers for handshake
  headers: {
    'Authorization': 'Bearer token123',
    'User-Agent': 'MyApp/1.0'
  },
  
  // TLS configuration
  tls: {
    ca: fs.readFileSync('ca.pem'),
    rejectUnauthorized: true
  },
  
  // WebSocket options
  ping: 30,
  maxLength: 1024 * 1024,
  
  // Proxy (if needed)
  proxy: {
    origin: 'http://proxy.company.com:8080'
  }
});

ws.on('open', function(event) {
  console.log('Connected:', ws.statusCode, ws.protocol);
  
  // Send initial message
  ws.send(JSON.stringify({
    type: 'subscribe',
    channels: ['updates', 'alerts']
  }));
});

ws.on('message', function(event) {
  try {
    const data = JSON.parse(event.data);
    console.log('Received:', data.type, data.payload);
  } catch (e) {
    console.log('Non-JSON message:', event.data);
  }
});

ws.on('error', function(event) {
  console.error('WebSocket error:', event.message);
});

ws.on('close', function(event) {
  console.log('Connection closed:', event.code);
  if (event.code !== 1000) {
    console.log('Abnormal close reason:', event.reason);
  }
});

// Graceful shutdown
process.on('SIGINT', function() {
  ws.close(1000, 'Client shutting down');
});

Protocol Support

// Protocol negotiation
const ws = new WebSocket.Client('ws://example.com/', ['chat', 'echo']);

ws.on('open', function() {
  // Check which protocol was selected
  console.log('Using protocol:', ws.protocol || 'none');
});

Binary Data Handling

// Send binary data
const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04]);
ws.send(buffer);

// Receive binary data
ws.on('message', function(event) {
  if (Buffer.isBuffer(event.data)) {
    console.log('Binary data received:', event.data.length, 'bytes');
  }
});

docs

eventsource.md

index.md

websocket-client.md

websocket-server.md

tile.json