WSServer is a base class that should not be used directly. Instead, use one of its specialized implementations:
- WSServerPubSub - For Publish-Subscribe and RPC functionality
- WSServerRoomManager - For room-based communication and game state management
This documentation is provided for reference to understand the underlying functionality inherited by the specialized server classes.
The WSServer class provides the foundational WebSocket server functionality including:
- Client connection management with authentication
- Origin validation and client limits
- Automatic ping/pong keepalive mechanism
- Broadcasting capabilities
- Configurable logging system
- Message size validation
- Constructor
- Server Control
- Client Management
- Message Handling
- Authentication
- Logging
- Internal Methods
Creates a new WebSocket server instance.
Parameters:
options(object): Server configuration optionsport(number, optional): The port number to run the server on. Default:443maxNbOfClients(number, optional): Maximum number of allowed clients. Default:1000maxInputSize(number, optional): Maximum size of input messages in bytes. Default:100000(100KB)origins(string, optional): Allowed origins for CORS. Use'*'for any origin or specify allowed origins. Default:'*'pingTimeout(number, optional): The timeout in milliseconds for ping/pong keepalive mechanism. Default:30000authCallback(function, optional): Authentication callback function. Default:(token, request, wsServer) => ({})- Parameters:
(token, request, wsServer)token(string|null): Authentication token sent by client via subprotocolrequest(http.IncomingMessage): The HTTP upgrade request. Contains headers includingrequest.headers.cookie.wsServer(WSServer): The server instance
- Returns: Object with custom metadata to store for the client, or
falseto reject the connection - Note: For cookie-based authentication (e.g., JWT in HTTP-only cookies), parse
request.headers.cookieto extract and verify the authentication token.
- Parameters:
logLevel(string, optional): Log level:'none','error','warn','info','debug'. Default:'info'logger(object, optional): External logger instance with methods:error,warn,info,debug. Default:null
Starts the WebSocket server and begins accepting client connections.
Parameters:
options(object, optional): Additional options to pass to the underlying WebSocket server. These options are passed to thewslibrary'sWebSocketServerconstructor. See the ws documentation for available options.
Note: The port, origins, and maxNbOfClients properties set in the WSServer constructor will override any corresponding values in the options parameter.
Common WebSocket Server Options:
server(http.Server|https.Server): A pre-created Node.js HTTP/S serverbacklog(number): Maximum length of the queue of pending connectionsperMessageDeflate(boolean|object): Enable/disable permessage-deflate compression
For a complete list of options, refer to the ws library documentation.
Example:
// Basic start
wsServer.start();
// Use with an existing HTTP server
import http from 'http';
const httpServer = http.createServer();
httpServer.listen(8080);
wsServer.start({
server: httpServer,
path: '/ws' // Optional: specify WebSocket path
});For a complete example with HTTP server serving client files, see the RPC with HTTP server example.
Closes the WebSocket server, disconnects all clients, and stops the ping interval.
Example:
wsServer.close();
// All clients disconnected, server stoppedGets the WebSocket client connection by client ID.
Parameters:
id(string): The client ID (UUID)
Returns: WebSocket|null - The WebSocket client object if found, null otherwise
Example:
const clientId = 'some-uuid-here';
const clientSocket = wsServer.getClientSocket(clientId);
if (clientSocket) {
wsServer.send(clientSocket, 'Hello specific client!');
}Gets an array of all connected clients' metadata.
Returns: Array - Array of client metadata objects
Example:
const allClients = wsServer.geClientsData();
console.log(`${allClients.length} clients connected`);
for (const client of allClients) {
console.log(`Client ${client.id}: ${client.username}`);
}Sends a message to a specific client. Only sends if the client connection is open.
Parameters:
client(WebSocket): The client WebSocket connectionmessage(string): The message to send
Example:
// Find client by ID
const client = wsServer.getClientSocket(clientId);
if (client) {
wsServer.send(client, JSON.stringify({
type: 'notification',
text: 'Hello!'
}));
}Broadcasts a message to all connected clients.
Parameters:
message(string): The message to broadcast
Example:
wsServer.broadcast(JSON.stringify({
type: 'announcement',
text: 'Server maintenance in 5 minutes'
}));Broadcasts a message to all clients except the specified one.
Parameters:
client(WebSocket): The client to exclude from the broadcastmessage(string): The message to broadcast
Example:
// When a user joins, notify all other users
wsServer.broadcastOthers(client, JSON.stringify({
type: 'user-joined',
userId: wsServer.clients.get(client).id
}));Sends an authentication success message to the client. Called automatically after successful authentication.
Parameters:
client(WebSocket): The client WebSocket connection
Message format:
{
"action": "auth-success",
"id": "client-uuid"
}Sends an authentication failure message to the client. Called automatically when authentication fails.
Parameters:
client(WebSocket): The client WebSocket connection
Message format:
{
"action": "auth-failed"
}Logs a message with the specified level. Messages are only logged if they match or exceed the configured log level.
Parameters:
message(string): The message to loglevel(string, optional): The log level:'error','warn','info','debug'. Default:'info'
Log Format:
- With external logger:
[WSS] ${message} - Without external logger:
[WSS][${timestamp}][${LEVEL}] ${message}
Example:
wsServer.log('Server started successfully', 'info');
wsServer.log('Configuration loaded', 'debug');
wsServer.log('Connection attempt failed', 'warn');
wsServer.log('Critical error occurred', 'error');The following methods are used internally by the server and typically don't need to be called directly:
Manages the ping/pong keepalive mechanism. Automatically called at intervals defined by pingTimeout. Terminates clients that don't respond to pings.
Creates metadata for a new client connection, combining a generated UUID with custom metadata from authCallback.
Parameters:
client(WebSocket): The client WebSocket connectioncustomMetadata(object): Custom metadata returned byauthCallback
Handles new client connections, including:
- Extracting authentication token from subprotocol
- Calling
authCallbackfor authentication - Creating client metadata
- Setting up event listeners (message, close, error, pong)
Handles incoming messages from clients. Default implementation broadcasts received messages to all clients. Override this method in subclasses for custom message handling.
Handles client disconnection and cleanup. Removes client from the clients Map.
Handles client errors and closes the connection.
Handles pong responses from clients, marking them as alive for the keepalive mechanism.
Type: Map<WebSocket, Object>
A Map containing all connected clients and their metadata. Each entry maps a WebSocket client to an object containing:
id(string): Auto-generated UUID for the client- Additional custom properties from
authCallback
Example:
for (const [socket, metadata] of wsServer.clients.entries()) {
console.log(`Client ${metadata.id}:`, metadata);
}Type: WebSocketServerOrigin|null
The underlying WebSocket server instance. null when not started.
- The default
onMessageimplementation simply broadcasts all messages to all clients - Message size is validated against
maxInputSize- oversized messages cause client disconnection - The ping/pong mechanism automatically removes unresponsive clients
- Client IDs are auto-generated UUIDs - use
authCallbackto add custom identification - Origin validation is handled by the underlying
WebSocketServerOriginclass
- WSServerPubSub - Recommended for PubSub/RPC applications
- WSServerRoomManager - Recommended for room-based applications