I have a tcp socket server written in Node js. I have an array globally declared in which I want to store all the socket clients. The issue is that since I am working with node cluster the array doesn't keep the data and keep on reseting whenever new data arrives from any of the client. Below is my code
const cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var sockets = [];
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('death', function(worker) {
// console.log('worker ' + worker.pid + ' died');
cluster.fork();
});
} else {
net.createServer(function(socket) {
// console.log('received connection...');
socket.on("error", function(err) {
// console.log("socket error: ")
// console.log(err.stack);
socket.destroy();
});
socket.on('data', function(data) {
sockets.push(socket);
console.log("existing socket clients" + sockets);
});
});
}
socket array only keeps the current data record and not the existing socket clients. But if I write this code without cluster then it keeps sockets data into array and code works fine
var sockets = [];
net.createServer(function(socket) {
// console.log('received connection...');
socket.on("error", function(err) {
// console.log("socket error: ")
// console.log(err.stack);
socket.destroy();
});
socket.on('data', function(data) {
sockets.push(socket);
console.log("existing socket clients" + sockets);
});
});
Thanks in advance