'Socket IO with cluster on https not working
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);
});
}
Solution 1:[1]
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.
Solution 2:[2]
According to https://github.com/socketio/socket.io-sticky
this module is not compatible with an HTTPS server
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anuj Bajpai |
| Solution 2 | Babak Yaghoobi |
