正常closures一个节点.JS HTTP服务器
这是我正在工作的一个简单的networking服务器
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 :)
除了保持活力以外,它们都很棒。 当第一个请求进来时, server.close
被调用。 但是这个过程并没有结束。 实际上,TCP连接仍然是打开的,这就允许另一个请求通过,这是我想要避免的。
我如何closures现有的保持连接?
你可以在响应callback中调用request.connection.destroy()
。 这将closures请求连接。
它也将结束你的过程,因为没有什么可做的,最终的结果和在那里调用process.exit()
是一样的。
您可以控制连接的空闲超时,因此您可以设置保持连接保持打开状态的时间。 例如:
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); });
我们可以用netcattesting这个:
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
after 4 seconds, the connection closes
现在我们可以显示closures服务器的工作原理:在所有的空闲连接断开后,服务器退出:
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
after 4 seconds, the connection closes and the server exits
如果您正在closures服务器,作为正常closures进程的一部分,则只需要这样做:
var server = require('http').createServer(myFancyServerLogic); server.on('connection', function (socket) {socket.unref();}); server.listen(80); function myFancyServerLogic(req, res) { req.connection.ref(); res.end('Hello World!', function () { req.connection.unref(); }); }
基本上,服务器使用的套接字只会在实际提供请求时使进程保持活动状态。 当他们只是坐在那里(因为一个Keep-Alive连接),一个调用server.close()
将会closures这个进程,只要没有别的东西让进程保持活着状态。 如果在服务器closures后需要做其他事情,作为正常关机的一部分,您可以挂接到process.on('beforeExit', callback)
来完成正常的closures过程。