Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda