当我使用节点 v6.17 运行此代码时,它表明保持活动状态不起作用
function notifyNotKeptAlive(httpObject, eventName, httpObjectName){
httpObject.on(eventName, function(socket){
socket.on('close', function(){
console.log("Yeeouch ! "+httpObjectName+" connection was not kept alive!");
});
});
}
var http=require('http');
var count=1;
var srv = http.createServer(function (req, res) {
var secs;
if ( (count%2)==1){secs=3;}
else {secs=1;}
console.log("Got http request #"+count+" so server waits "+secs+" seconds to respond");
var countForThisClosure=count;
setTimeout(function(){
console.log("Waking up from sleep of "+secs);
res.writeHead(200, {'Content-Type': 'text/plain'});
if (secs===3){
res.end('Visit #'+countForThisClosure+' costing a wait of '+secs+' seconds !!');
} else {
res.end('Visit #'+countForThisClosure+' costing a wait of '+secs+' seconds !!');
}
}, secs*1000);
count++;
}).listen(8090);
notifyNotKeptAlive(srv, 'connection', 'http server');
for (var i=0;i<2;i++){
var req=http.request( {'host': 'localhost', 'port':8090}, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('INCOMING <---' + chunk);
});
}
);
notifyNotKeptAlive(req, 'socket', 'http client');
req.end();
}
仅当我在 Epeli 提供的 http lib 源代码的第 1263 行添加了一个感叹号时,它才起作用。因此,下面的行“if (req.shouldKeepAlive){”应该改为“if (!req.shouldKeepALive){” res.on('end', function() {
if (req.shouldKeepAlive) {
socket.removeListener('close', closeListener);
socket.removeListener('error', errorListener);
socket.emit('free');
}
});
此行位于从第 1113 行开始的 ClientRequest.prototype.onSocket 闭包中设置的 on 'end' 回调中。
此 http lib 源的链接是(与 Epeli 的相同)https://github.com/joyent/node/blob/e8067cb68563e3f3ab760e3ce8d0aeb873198f36/lib/http.js#L889