正常关闭node.JS HTTP服务器

Bry*_*eld 28 http exit node.js

这是我正在处理的简单网络服务器

var server = require("http").createServer(function(req,resp) {
    resp.writeHead(200,{"Content-Type":"text/plain"})
    resp.write("hi")
    resp.end()
    server.close()
})
server.listen(80, 'localhost')
// The shortest webserver you ever did see! Thanks to Node.JS :)
Run Code Online (Sandbox Code Playgroud)

除了保持活力之外,效果很好.当第一个请求进入时,server.close会被调用.但这个过程并没有结束.实际上TCP连接仍然是打开的,这允许另一个请求通过,这是我试图避免的.

如何关闭现有的保持连接?

小智 24

您可以控制连接的空闲超时,以便设置保持活动连接保持打开的时间.例如:

server=require('http').createServer(function(req,res) {
    //Respond
    if(req.url.match(/^\/end.*/)) {
        server.close();
        res.writeHead(200,{'Content-Type':'text/plain'});
        res.end('Closedown');
    } else {
        res.writeHead(200,{'Content-Type':'text/plain'});
        res.end('Hello World!');
    }
}).listen(1088);
//Set the idle timeout on any new connection
server.addListener("connection",function(stream) {
    stream.setTimeout(4000);
});
Run Code Online (Sandbox Code Playgroud)

我们可以用netcat测试一下:

ben@quad-14:~/node$ echo -e "GET /test HTTP/1.1\nConnection: keep-alive\n\n" | netcat -C -q -1 localhost 1088
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked

c
Hello World!
0

Run Code Online (Sandbox Code Playgroud)

after 4 seconds, the connection closes

现在我们可以证明关闭服务器的工作原理:在删除所有空闲连接后,服务器退出:

ben@quad-14:~/node$ echo -e "GET /end HTTP/1.1\nConnection: keep-alive\n\n" | netcat -C -q -1 localhost 1088
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked

9
Closedown
0
Run Code Online (Sandbox Code Playgroud)

after 4 seconds, the connection closes and the server exits


Ric*_*asi 19

您可以调用request.connection.destroy()响应回调.这将关闭请求连接.

它也将结束你的过程,因为没有什么可做的,最终的结果就像process.exit()在那里呼叫一样.

  • 我不想消除保持活动功能,其唯一目的是轻松关闭Web服务器.在`resp.end()`时,它可能不知道它将在接下来的几秒内关闭(在连接自动被破坏之前).因此它不会知道它应该破坏连接.这就是它将添加到数组的原因.但实际上,有可能有一个永远不会发出第一个请求的连接,这意味着我的第一个注释不能作为解决方案,退出可能是我最好的选择(缺少克隆`http.js`源代码). (6认同)