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

207
Views
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
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!