如何正确`closures`一个node.js服务器?
根据调用server.close()
的文档
阻止服务器接受新连接并保持现有连接。
所以我的代码是:
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的评论,即使我closuresgetConnections
callback以外的服务器,问题依然存在。
var server = http.createServer(function (req, res) { console.log('path: ' + req.url); res.end(new Date() + ''); server.close(); });
您在问题中发布了解决scheme。
阻止服务器接受新连接并保持现有 连接 。
换句话说,你打开的连接在超时之前保持打开状态。 这被称为keep-alive
连接 。
在调用server.close();
之后立即closures所有连接的方法,请参阅这个答案how-do-i-shutdown -a-node-js-https-server-immediately server.close();
方法。