如何避免nodejs express应用中出现太多的http连接

现象

正常情况下,基于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();
}
相关推荐
Johnstons2 小时前
Wireshark ExpertInfo是什么?一文讲透异常分级、适用场景、和传统抓包阅读的区别与排查标准
网络·测试工具·wireshark·es
alxraves2 小时前
医疗器械软件注册指导原则注意事项
网络·安全·健康医疗·制造
liann1194 小时前
3.2_红队攻击框架--MITRE ATT&CK‌
python·网络协议·安全·网络安全·系统安全·信息与通信
GCKJ_08245 小时前
观成科技:利用DoH加密通信的恶意木马流量分析
网络
zjun10016 小时前
TCP专栏-1.TCP协议概念说明
网络·网络协议·tcp/ip
德迅云安全杨德俊6 小时前
DDoS 解析与防御体系
网络·安全·web安全·ddos
国科安芯7 小时前
商业航天电机控制领域抗辐射 MCU 芯片应用研究
网络·单片机·嵌入式硬件·安全性测试
Lentou7 小时前
日志轮询策略
linux·服务器·网络
星融元asterfusion7 小时前
如何为您的网络选择正确的PTP配置文件:一份实用指南
网络·ptp·时间同步
光路科技7 小时前
一文讲透DHCP Snooping:从原理到工业网络实践
网络