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()
在那里呼叫一样.