http - 正常关闭 node.JS HTTP 服务器

标签 http node.js exit

这是我正在开发的一个简单的网络服务器

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

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

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

最佳答案

您可以控制连接的空闲超时,因此您可以设置保持事件连接保持打开状态的时间。例如:

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);
<b>//Set the idle timeout on any new connection
server.addListener("connection",function(stream) {
    stream.setTimeout(4000);
});</b>

我们可以用 netcat 测试一下:

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

c
Hello World!
0

4 秒后,连接关闭

现在我们可以证明关闭服务器是有效的:在所有空闲连接被删除后,服务器退出:

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

9
Closedown
0

4 秒后,连接关闭,服务器退出

关于http - 正常关闭 node.JS HTTP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13747496/

相关文章:

api - 报告 API 中不兼容列的 HTTP 状态代码

angular - Angular 5 上的 HTTP header

WPF 命令行

android - 为什么我们使用 ApacheHttpClient 而不是 HttpURLConnection?

android - Spring Android 的 Http PATCH

node.js - 无法使用 Node.js 中的 child_process exec 调用解析目录路径

node.js - TypeORM 无法将 cli 与配置一起使用

json - 如何在 Node.js 中替换 JSON 对象中的值

docker - 如何处理 Docker 中的状态 "Exit 0"

c++ - 我们可以在 C++ 的构造函数中调用 exit() 吗?