Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 413
Aviv Cohn Avatar asked Jan 17 '15 22:01

Aviv Cohn


1 Answers

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.

like image 160
matth Avatar answered Sep 17 '22 16:09

matth