Вы можете контролировать время простоя для соединения, поэтому вы можете установить, как долго соединение активности остается открытым.Например:
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
after 4 seconds, the connection closes
И теперь мы можем показать, что закрытиесервер работает: после сброса всех бездействующих соединений сервер завершает работу:
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
after 4 seconds, the connection closes and the server exits