Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Socket Array does not storing socket clients data and keep on reseting on each client data arrives

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!