8

Based on the Socket IO documentation, I am able to use http but not https. I am using the socket io with cluster with http its working fine but not working when i implement https on it.
Socket IO documentation that i am using :- https://socket.io/docs/v4/cluster-adapter/

My Code is

const cluster = require("cluster");
const https = require("https");
var fs = require("fs");
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");
const sslOptions = {
  key: fs.readFileSync("security/cert.key"),
  cert: fs.readFileSync("security/cert.pem")
};
const options = { cors: true, origins: "*" };
if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  const httpServer = https.createServer(sslOptions);

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

  setupPrimary();

  cluster.setupPrimary({
    serialization: "advanced"
  });

  httpServer.listen(8000);

  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 = https.createServer(sslOptions);

  const io = new Server(httpServer, options);

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

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

  io.on("connection", (socket) => {
    console.log("connected" + process.pid);
    io.emit("data", "connected to worker: " + cluster.worker.id);
  });
}
MarioG8
  • 5,122
  • 4
  • 13
  • 29
Lalit yogi
  • 81
  • 2
  • 1
    Can you describe what "not working" exactly means? Do you have any error messages? What behaviour do you face and what would you expect? . – Silvan Bregy Dec 06 '21 at 14:35
  • @SilvanBregy Thanks for response Socket IO is not connecting from client side. And also if Socket IO is running on your port then socketio.js file generated automatically but here not showing any socketio.js file. Same I run with http its working fine – Lalit yogi Dec 07 '21 at 07:10
  • try this answer with express.js, (https://stackoverflow.com/a/38525463/13460667). I know this is not what you asked, but you can try to find anything you are missing. – Rajan Dec 21 '21 at 08:08

2 Answers2

0

There's no problem with code, the possible error could be "Secure Connection Failed" due to ssl certificate.Otherwise the same code is working for me.

Anuj Bajpai
  • 9
  • 1
  • 3
  • Thanks @anuj I have tested SSL its working fine. because If I am using without clustering its working fine . – Lalit yogi Jan 03 '22 at 04:39
0

According to https://github.com/socketio/socket.io-sticky

this module is not compatible with an HTTPS server

Babak Yaghoobi
  • 1,892
  • 9
  • 18