Node.js http.request keepAlive

时间:2019-05-22 10:42:42

标签: javascript node.js http

我正在尝试在http.Agent({ keepAlive: true})上使用http.request来保持连接打开以供将来使用。

我创建了一个用于记录每个新连接的简单服务器,但是当我运行 request.js 时,该服务器记录了两个新连接。

如何将HTTP保持活动与Node.js本机模块一起使用?

request.js:

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

2 个答案:

答案 0 :(得分:2)

设置maxSockets个这样的选项:

const agent = new http.Agent({
    keepAlive: true,
    maxSockets: 1
});

默认情况下,maxSockets设置为Infinity-https://nodejs.org/api/http.html#http_new_agent_options

节点v10上的完整示例

const http = require("http");

const agent = new http.Agent({
    keepAlive: true,
    maxSockets: 1
});

var req1 = http.request({
    agent: agent,
    method: "GET",
    hostname: "localhost",
    port: 3000
}, function (res1) {
    console.log("REQUEST_1");

    res1.on('data', function () {
        console.log("REQUEST_1 data");
    });

    res1.on('end', function () {
        console.log("REQUEST_1 end");
    });

    var req2 = http.request({
        agent: agent,
        method: "GET",
        hostname: "localhost",
        port: 3000
    }, function (res2) {
        console.log("REQUEST_2");

        res2.on('data', function () {
            console.log("REQUEST_2 data");
        });

        res2.on('end', function () {
            console.log("REQUEST_2 end");
        });
    });
    req2.end();
});
req1.end();

答案 1 :(得分:0)

接受的答案不能明确表明所发布的代码将仅允许每个主机每个线程同时一个请求。

通常这不是您想要的,并且会导致请求变慢,等待上一个请求完成。