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

208
Visualizações
nodejs tcp server socket object is local

I try to make a nodejs tcp server. In the server.on('connection',...) callback the socket object is not local variable? How can stay alive because the communication is still working if I cant pack the socket to an array. My goal is to pack the sockets to an array and handle they from there. I implemented a timeout, to remove unused sockets, but if I delete a socket from the array I experience also a timeout if I didn't remove it. So, I think i have a duplicate of every socket in the background. How can I make that the sockets exist only in the array?

// Include Nodejs' net module.
const Net = require('net');
// The port on which the server is listening.
const port = 8080;

clients = [];

const server = new Net.Server();

server.listen(port, function() {
    console.log(`Server listening for connection requests on socket localhost:${port}`.);
});


server.on('connection', function(socket) {
    console.log('A new connection has been established.');

    
    socket.write('Hello, client.');

    socket.on('data', function(chunk) {
        console.log(`Data received from client: ${chunk.toString()`.});
    });

    socket.on('end', function() {
        console.log('Closing connection with the client');
    });

    socket.on('error', function(err) {
        console.log(`Error: ${err}`);
    });

    socket.timeoutHandle = setTimeout(() => {
        console.log(`client timed out: ${socket.name}`);
        socket.end();
        socket.destroy();
        clients.forEach((client, index) => {
          if (client.remoteAddress == socket.remoteAddress) {
            clients.splice(index, 1);
          }
        });
      }, 15000);

    clients.push(socket);
});
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