0

Get Socket Ref On Socket Close

Following this SO answer, I expect to be able to shutdown the server and restart it again. To do that accountably, it sounds like I need to not just call close() on the server instance object but also any remaining open sockets. Memory Leaks are an issue so I would like to store the socket instances in a Set and clean up expired connections as they close.

You need to

  1. subscribe to the connection event of the server and add opened sockets to an array
  2. keep track of the open sockets by subscribing to their close event and removing the closed ones from your array
  3. call destroy on all of the remaining open sockets when you need to terminate the server
...
const sockets = new Set();  // use a set to easily get/delete sockets
...
function serve(compilations) {
    const location = './dist', directory = express.static(location);
    const server = app
        .use('/', log, directory)
        .get( '*', (req, res) => res.redirect('/') )
        .listen(3000)
        ;
    server.on('connection', handleConnection);  // subscribe to connections (#1)
    console.log(`serving...(${location})`);
    
    return server;
}
...
function handleSocketClose(socket, a, b, ...x) {  // @param#socket === false (has-error sentinel) (#2.2)
    const closed = sockets.delete(socket);
    console.log(`HANDLE-SOCKET-CLOSE...(${sockets.size})`, closed, a, b);  // outputs "HANDLE-SOCKET-CLOSE...(N) false undefined undefined"
}

function handleConnection(socket) {
    sockets.add(socket);  // add socket/client to set (#1)
    console.log(`HANDLE-CONNECTION...(${sockets.size})`);
    socket.on('close', handleSocketClose);  // subscribe to closures on individual sockets (#2.1)
}

From the SO answer (above), I have #1 & #3 completed. In fact, I even have, say, #2.1 done as I am currently listening on each socket to for the close event -- which does fire. The problem is, say, #2.2: "...and removing the closed ones from your array".

My expectation while implementing the handleSocketClose callback was that one of the argument values would be the socket object, itself, so that I could then cleanup the sockets collection.

Question

How in Laniakea can I obtain a reference to the socket in question at close time (without iteration and checking the connection status)?

Cody
  • 9,352
  • 4
  • 57
  • 45

0 Answers0