Server-side WebSocket implementation that handles HTTP upgrade requests and manages WebSocket connections with full protocol compliance.
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);
});
}
});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);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);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 transmissionws.readable; // Boolean - Stream readable state
ws.writable; // Boolean - Stream writable stateSends 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);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');
});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 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 processingFired when the WebSocket connection is established.
ws.on('open', function(event) {
// Connection is ready for communication
});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);
});Fired when a protocol error occurs.
ws.on('error', function(event) {
// event.message contains error description
console.log('Error:', event.message);
});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);
});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 */ };// 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
});// 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);// Add WebSocket extensions
const deflate = require('permessage-deflate');
const ws = new WebSocket(request, socket, body, [], {
extensions: [deflate]
});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);
}
});