Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@socket.io/cluster-adapter

socketio20.7kMIT0.2.2TypeScript support: included

The Socket.IO cluster adapter, allowing to broadcast events between several Socket.IO servers

socket.io, cluster, adapter

readme

Socket.IO cluster adapter

The `@socket.io/cluster-adapter` package allows broadcasting packets between multiple Socket.IO servers.

Adapter diagram

It can be used in conjunction with @socket.io/sticky to broadcast packets between the workers of the same Node.js cluster.

Supported features:

Related packages:

Table of contents

Installation

npm install @socket.io/cluster-adapter

Usage

const cluster = require("cluster");
const http = require("http");
const { Server } = require("socket.io");
const numCPUs = require("os").cpus().length;
const { setupMaster, setupWorker } = require("@socket.io/sticky");
const { createAdapter, setupPrimary } = require("@socket.io/cluster-adapter");

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  const httpServer = http.createServer();

  // setup sticky sessions
  setupMaster(httpServer, {
    loadBalancingMethod: "least-connection",
  });

  // setup connections between the workers
  setupPrimary();

  // needed for packets containing buffers (you can ignore it if you only send plaintext objects)
  // Node.js < 16.0.0
  cluster.setupMaster({
    serialization: "advanced",
  });
  // Node.js > 16.0.0
  // cluster.setupPrimary({
  //   serialization: "advanced",
  // });

  httpServer.listen(3000);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on("exit", (worker) => {
    console.log(`Worker ${worker.process.pid} died`);
    cluster.fork();
  });
} else {
  console.log(`Worker ${process.pid} started`);

  const httpServer = http.createServer();
  const io = new Server(httpServer);

  // use the cluster adapter
  io.adapter(createAdapter());

  // setup connection with the primary process
  setupWorker(io);

  io.on("connection", (socket) => {
    /* ... */
  });
}

License

MIT

changelog

History

Release notes

0.2.2 (2023-03-24)

The socket.io-adapter package was added to the list of peerDependencies, in order to fix sync issues with the version imported by the socket.io package (see 15fd56e).

Support for connection state recovery (see here) will be added in the next release.

0.2.1 (2022-10-13)

Bug Fixes

  • properly handle ERR_IPC_CHANNEL_CLOSED errors (#6) (be0a0e3)

0.2.0 (2022-04-28)

Features

  • broadcast and expect multiple acks (055b784)

This feature was added in `socket.io@4.5.0`:

io.timeout(1000).emit("some-event", (err, responses) => {
  // ...
});

Thanks to this change, it will now work within a Node.js cluster.

0.1.0 (2021-06-22)

Initial commit