SocketCluster Server

20.0.0 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Demonstrates how to attach SocketCluster server to an HTTP server and handle inbound connections, RPC procedures, and remote events using async iterators. It also shows transmitting a basic event to connected clients.

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');
});

view raw JSON →