SocketCluster Server
SocketCluster Server (version 20.0.0) is the core server-side module for the SocketCluster real-time framework, designed to facilitate highly scalable, event-driven applications using WebSockets. It operates by attaching to an existing Node.js HTTP/HTTPS server and provides robust mechanisms for managing inbound connections, handling Remote Procedure Calls (RPCs), and processing real-time event streams. A key differentiator and architectural shift in recent major versions is its adoption of modern JavaScript async iterators (`for-await-of` loops) for stream processing, moving away from traditional `EventEmitter` patterns. This paradigm promotes more readable, succinct, and less error-prone code by reducing callback hell and simplifying resource management, as listeners do not need explicit unbinding. While it maintains a compatibility mode for older clients (protocolVersion 1), the current stable version encourages the use of its async iterable API. Releases tend to align with major Node.js LTS updates or significant architectural improvements.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use CommonJS `require` syntax in an ES Module context without proper configuration.fixIf running in an ES Module environment (e.g., `"type": "module"` in `package.json`), change import statements to `import * as socketClusterServer from 'socketcluster-server';` or configure your build tool for CommonJS compatibility. -
Client failed to connect: Invalid protocol version
cause The client is attempting to connect using an older SocketCluster protocol version, but the server is expecting a newer one (or vice-versa).fixEnable compatibility mode on the server: `socketClusterServer.attach(httpServer, { protocolVersion: 1 });` or update your client to use a compatible `socketcluster-client` version and its default protocol. -
TypeError: agServer.listener is not a function
cause This error likely indicates that `agServer` was not correctly initialized, or an incorrect method name was called, possibly due to an API change in major versions.fixEnsure `agServer` is correctly created using `socketClusterServer.attach(httpServer);` and that you are using the `listener()` method as shown in the v16+ documentation for async iterators. -
Error: listen EADDRINUSE: address already in use :::8000
cause The specified port (e.g., 8000) for the HTTP server is already in use by another process or a previous instance of the server was not properly shut down.fixChange the `httpServer.listen()` port to an available one, or ensure no other applications are using the desired port. On Linux, `lsof -i :8000` can identify the process to terminate.
Warnings
- breaking Upgrading from SocketCluster Server v15.x or earlier to v16.x and above (including v20.0.0) involves a significant API shift from `EventEmitter` patterns to async iterators (`for-await-of` loops). Code relying on `on()`, `addListener()`, or `removeListener()` will need to be refactored.
- gotcha To ensure compatibility with older SocketCluster clients (e.g., those using `socketcluster-client` v14.x or earlier), you must explicitly set `protocolVersion: 1` and potentially `path: '/socketcluster/'` during server attachment. Failure to do so will result in client connection errors.
- gotcha While `socketcluster-server` can operate independently, a complete real-time application setup typically requires `socketcluster-client` for browser or Node.js clients to connect and interact. For development and testing, both packages are generally needed to form a functional system.
- gotcha SocketCluster Server heavily leverages modern JavaScript features like `async/await` and `for-await-of` loops. Ensure your Node.js environment is sufficiently recent (e.g., Node.js 12+ for full compatibility) to avoid syntax errors or unexpected behavior.
Install
-
npm install socketcluster-server -
yarn add socketcluster-server -
pnpm add socketcluster-server
Imports
- socketClusterServer
import socketClusterServer from 'socketcluster-server';
const socketClusterServer = require('socketcluster-server'); - AGServer
import { AGServer } from 'socketcluster-server';import type { AGServer } from 'socketcluster-server'; - AGSocket
import { AGSocket } from 'socketcluster-server';import type { AGSocket } from 'socketcluster-server';
Quickstart
const http = require('http');
const socketClusterServer = require('socketcluster-server');
let httpServer = http.createServer();
let agServer = socketClusterServer.attach(httpServer);
(async () => {
// Handle new inbound sockets.
for await (let {socket} of agServer.listener('connection')) {
(async () => {
// Set up a loop to handle and respond to RPCs for a procedure.
for await (let req of socket.procedure('customProc')) {
if (!req.data) {
let error = new Error('Server failed to execute the procedure');
error.name = 'BadCustomError';
req.error(error);
} else {
req.end('Success');
}
}
})();
(async () => {
// Set up a loop to handle remote transmitted events.
for await (let data of socket.receiver('customRemoteEvent')) {
console.log(`Received customRemoteEvent: ${data}`);
}
})();
socket.transmit('helloClient', { message: 'Hello from server!' });
}
})();
httpServer.listen(8000, () => {
console.log('SocketCluster Server listening on port 8000');
});