How to properly close a Node.js TCP server?

与世无争的帅哥 提交于 2019-12-22 03:48:42

问题


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?


回答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.



来源:https://stackoverflow.com/questions/28004856/how-to-properly-close-a-node-js-tcp-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!