var http = require('http');
var server = http.createServer().listen(4000);
server.on('close', function () {
console.log('close event', Date.now());
});
server.on('request', function (req, res) {
console.log('request', Date.now());
server.close(function () {
console.log('server closed!', Date.now());
});
res.end('res ok');
})
Why can't the close
event be triggered after using server.close()
?
Look at the HTTP API description:
Stop the server receiving new connections.
and TCP API description:
Causes the server to stop accepting new connections and only maintain existing connections. This function is asynchronous, when all connections are disconnected, the server is closed and the 'close' event is emitted...
It turns out that server.close()
just stops the server from receiving new connections, and does not directly shut down the server. Only when all connections are disconnected will the server be in a closed state and emit the close
event.
However, changing the code to a delayed call can directly shut down the server (of course, a HTTP
connection must be established within 5 seconds).
var http = require('http');
var server = http.createServer().listen(4000);
server.on('close', function () {
console.log('close event', Date.now());
});
server.on('request', function (req, res) {
console.log('request', Date.now());
res.end('res ok');
})
function closeServer() {
server.close(function () {
console.log('server closed!', Date.now());
});
}
setTimeout(function () {
closeServer();
}, 5000);
If you follow the description in the API, the close()
method just stops the server from receiving new connections. So, why can the server be shut down directly by changing to the latter method?
PHPz2017-05-16 13:44:34
The API description is correct. It's just that you misunderstood when testing. Both types of shutdown http services will eventually be shut down, but the running logic is different.
Code 1 will wait for you to establish an http connection without closing it until you request an http connection, and then close the http service 2 minutes after this request.
Code 2 will wait for you for 5 seconds. If you do not establish a connection within 5 seconds, the http service will be closed directly. If you request an http connection within 5 seconds, the http service will be closed 2 minutes after the request.
原来 server.close() 只是使服务器停止接收新连接,并没有直接操作关闭服务器。只有当所有连接都断开的时候,服务器才会处于关闭状态并且发射 close 事件。
问题在于什么时候算所有连接都断开
?
When you execute res.end('res ok');, the http connection is not closed because of your request Connection
是 keep-alive
. At this time, only the http service returns data, the browser renders the page, and the http connection is still open. Then if you have no new request within 2 minutes, the http connection will be closed this time. 2 minutes is the default timeout for http services (not http requests).
soonfy