Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda