Express.js应用程序不能干净地closuresserver.close()
我试图在应用程序closures时正确closuresMongoDB连接。 这里是代码:
var express = require('express') , http = require('http') , mongoose = require('mongoose') , path = require('path'); var app = express(); app.set('port', process.env.PORT || 3000); mongoose.connect('mongodb://localhost/test'); // some post and get handlers etc. (removed for shorter output) var server = app.listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); function cleanup () { server.close(function () { console.log("Closed out remaining connections."); mongoose.connection.close(); process.exit(); }); setTimeout( function () { console.error("Could not close connections in time, forcing shut down"); process.exit(1); }, 30*1000); } process.on('SIGINT', cleanup); process.on('SIGTERM', cleanup);
一切都很好,并在应用程序第一次启动时工作。 当它在启动后立即按下Ctrl-c
时,就会closuresClosed out remaining connections.
信息。 但是,一旦应用程序与数据库交互,甚至服务一个静态页面,我试图closures它,它退出时出现以下错误:
net.js:1225 throw new Error('Not running'); ^ Error: Not running at Server.close (net.js:1225:11) at process.cleanup (<...>/app.js:77:12) at process.EventEmitter.emit (events.js:92:17) at Signal.wrap.onsignal (node.js:756:46) 22 Aug 15:15:28 - [nodemon] exiting
任何想法是什么导致这个错误,我怎么能解决它?
当调用server.close时,有两个属性被检查。
handle<tcp handle> connections
负责这个错误的server.close的负责代码片段;
if (!this._handle) { // Throw error. Follows net_legacy behaviour. throw new Error('Not running'); }
只有在句柄=== null和连接=== 0的情况下调用传递给close的callback函数。
案例:服务器启动并发送没有服务的信号。
在结束之前,
handle === TCP handle. connection===0;
closures句柄后=== null; 连接=== 0;
callback被调用。
案例:服务器启动并在请求服务器之后发送信号。
在结束之前,
handle === TCP.handle; connection===1;
closures句柄后=== null; 连接=== 1;
没有callback被激发。
第二次按ctrl-c
在结束之前,
handle === null; connection===1;
由于句柄=== null,检查会引发你所看到的错误。
你的服务器打开连接的原因是你正在发送Connection: keep-alive
头文件。
摩根的答案干净地closures服务器上的所有连接,断开所有的客户端。
如果您只是testing您的应用程序,并希望在testing之前/之后干净地closures它,我build议发送Connection: close
标题和server.close()
将按预期工作。
我不认为设置server._connections = 0实际上closures连接。 它只是满足条件让你的callback执行。
你可能想尝试这样的事情:
// Everything else how you had it before ... var sockets = []; server.on('connection', function(socket) { sockets.push(socket); }); function cleanup () { server.close(function () { console.log("Closed out remaining connections."); // mongoose.connection.close(); Might want to comment this out process.exit(); }); // Add this part to manually destroy all the connections. sockets.forEach(function(socket) { socket.destroy(); }); // setTimeout() ... }