我正在尝试在http.request
上使用http.Agent({ keepAlive: true})
来保持连接以备将来的请求。
我创建了一个简单的服务器来记录每个新连接,但是当我运行我的request.js时,服务器会记录两个新连接。
如何在Node.js本地模块中使用HTTP keep-alive?
request.js:
Original Answer翻译成"最初的回答"
const http = require("http");
const agent = new http.Agent({
keepAlive: true
});
var req1 = http.request({
agent: agent,
method: "GET",
hostname: "localhost",
port: 3000
}, function (res1) {
console.log("REQUEST_1");
var req2 = http.request({
agent: agent,
method: "GET",
hostname: "localhost",
port: 3000
}, function (res2) {
console.log("REQUEST_2");
});
req2.end();
});
req1.end();
server.js:
const http = require('http');
var server = http.createServer(function (req, res) {
res.end('OK');
console.log("REQUEST");
})
server.on('connection', function (socket) {
console.log("NEW CONNECTION");
})
server.listen(3000);
输出:
NEW CONNECTION
REQUEST
NEW CONNECTION
REQUEST
end
事件,但我已将其添加以覆盖所有情况。 - kuba