如何正确关闭Node.js TCP服务器? [英] How to properly close a Node.js TCP server?

查看:459
本文介绍了如何正确关闭Node.js TCP服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在Google或SO上找到明确的答案。

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

我知道 net.Server 实例有一个 close 方法,该方法不允许任何其他客户端。但它不会断开已连接的客户端。我怎么能实现这个目标呢?

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?

我知道如何用Http做到这一点,我想我问的是它与Tcp是否相同或者是否不同。

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.

使用Http,我会做这样的事情:

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

Tcp是否相同?或者我应该做些什么不同的事情?

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

推荐答案

由于没有提供答案,这里有一个如何打开和(硬)的例子关闭node.js中的服务器:

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

创建服务器:

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

关闭服务器:

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

更新由于使用上述代码,我遇到了问题关闭将使端口保持打开状态(Windows中为TIME_WAIT)。由于我故意关闭连接,因此我正在使用 unref 关闭tcp服务器,但如果这是关闭连接的正确方法,我不是100%。

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.

这篇关于如何正确关闭Node.js TCP服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆