按照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