Node.js http.request keepAlive

isf*_*ior 4 javascript http node.js

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

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

如何将 HTTP keep-alive 与 Node.js 本机模块一起使用?

请求.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();
Run Code Online (Sandbox Code Playgroud)

服务器.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);
Run Code Online (Sandbox Code Playgroud)

输出:

NEW CONNECTION
REQUEST
NEW CONNECTION
REQUEST
Run Code Online (Sandbox Code Playgroud)

kub*_*uba 5

设置maxSockets选项如下:

const agent = new http.Agent({
    keepAlive: true,
    maxSockets: 1
});
Run Code Online (Sandbox Code Playgroud)

默认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();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。现在它可以工作了,我没有处理请求的“数据”和“结束”事件。 (2认同)
  • 解释在这里:https://nodejs.org/dist/latest-v10.x/docs/api/http.html#http_class_http_clientrequest,以“如果没有添加‘响应’处理程序”开头。在这种情况下,您可以省略“end”事件,但我添加了此事件以涵盖所有内容。 (2认同)