'How to properly close a Node.js TCP server?

I couldn't find a clear answer on Google or SO.

I know a net.Server instance has a close method that doesn't allow any more clients in. But it doesn't disconnect clients already connected. How can I achieve that?

I know how this can be done with Http, I guess I'm asking if it's the same with Tcp or if it's different.

With Http, I'd do something like this:

var http = require("http");

var clients = [];

var server = http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end("You sent a request.");
});

server.on("connection", function(socket) {
    socket.write("You connected.");
    clients.push(socket);
});

// .. later when I want to close
server.close();
clients.forEach(function(client) {
    client.destroy();
});

Is it the same for Tcp? Or should I do anything differently?



Solution 1:[1]

Since no answer was provided, here is an example of how to open and (hard) close a server in node.js:

Create the server:

var net = require('net');

var clients = [];
var server = net.createServer();

server.on('connection', function (socket) {
    clients.push(socket);
    console.log('client connect, count: ', clients.length);

    socket.on('close', function () {
        clients.splice(clients.indexOf(socket), 1);
    });
});

server.listen(8194);

Close the server:

// destroy all clients (this will emit the 'close' event above)
for (var i in clients) {
    clients[i].destroy();
}
server.close(function () {
    console.log('server closed.');
    server.unref();
});

Update: Since using the above code, I've ran into an issue that close will leave the port open (TIME_WAIT in Windows). Since I'm intentionally closing the connection, I'm using unref as it appears to fully close the tcp server, though I'm not 100% if this is the correct way of closing the connection.

Solution 2:[2]

I am using NodeJS v16.13.2 ... When the process containing the server code exits, all clients connection are closed/destroyed by default.

I came here to find out how I could listen for a server.("exit", myTaskCallback), since I wanted to delete some files while exiting the server. But the answer I have found is that such event does not exists. I had to listen to process.on('exit', myTaskCallback) to do the job.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Eric Aya