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);
});