按照documentation调用server.close()
如何正确`关闭`一个node.js服务器?
停止接受新连接的服务器,并保持现有的连接。
所以我的代码是:
var http = require('http');
var server = http.createServer(function (req, res) {
console.log('path: ' + req.url);
server.getConnections(function (err, count) {
console.log('connections: ' + count);
res.end('end');
server.close();
});
});
server.listen(3000);
server.on('close', function() {
console.log('server closed');
process.exit(1);
});
这是我做请求http://localhost:3000
后得到:
> path:/ connections: 1
> path:/ connections: 1
>
> net.js:1236
> throw new Error('Not running');
> ^ Error: Not running
> at Server.close (net.js:1236:11)
这意味着,第二连接被接受,即使在第一个我叫server.close()
。
我错过了什么?
编辑:根据@ gino9的评论,即使我关闭getConnections
回调以外的服务器,问题仍然存在。
var server = http.createServer(function (req, res) {
console.log('path: ' + req.url);
res.end(new Date() + '');
server.close();
});
通过标志捕捉(特定)异常或跟踪手动关闭? – user2864740 2014-11-04 17:13:43
请注意,您从异步getConnections的回调中调用server.close(),然后无法确定在处理第二个请求之前服务器已关闭。 – matteo 2014-11-04 17:16:52
@ user2864740我这样做,并没有例外,但传入的请求不断被接受和服务。我的问题是为什么会发生这种情况? – simich 2014-11-04 17:17:18