现象

正常情况下基于nodejs的http通信应用在发送http.request时不管你是否使用agent和timeout/keepAlive客户端和服务器之间的连接数不会太多。但下面情况下在请求频繁时连接数可能会快速增长并且不会释放

客户端

http.request(...)

服务器端

express().use("/",(req,res)=>{
    
    return; //不回应

    res.send(`responed by server`);
    res.end();
});

也就是说如果服务端没有正确响应连接将会一直存在不管客户端如何调整请求参数。

解决方法

要解决这个问题有两个地方可以处理

服务端及时响应请求

express().use("/",(req,res)=>{
    res.send(`responed by server`);
    res.end();
});

这种情况下客户端无论是否使用agent是否keepAlive连接数都不会太多。

客户端超时后强制关闭

let req = http.request(...)
req.on('timeout', function() {
        console.error("request time out!");
    	//强制关闭连接
        req.destroy();
});

客户端优化

const express = require("express");
const http    = require('http');

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

function post(host,port,path,content,callback) {
    var data    = '';
    var options = {
        agent: agent,
        hostname: host,
        port: port,
        path: path,
        method: 'POST',
        timeout:2000,
        headers: {
            'Content-Type': 'application/json; charset=UTF-8',
            'Connection': 'Keep-Alive'
        }
    };
    var req = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            data = data + chunk;
        });
        res.on('end', () => {
            callback(null,data);
        });
    });

    req.on('error', function(e) {
        callback("error",e);
    });

    //这是重点
    req.on('timeout', function() {
        req.destroy();
        callback("timeout");
    });
    
    req.write(content);
    req.end();
}