如何避免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();
}
相关推荐
guts°22 分钟前
10-ACL技术
网络·网络协议
群联云防护小杜31 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
en-route1 小时前
Http请求中的特殊字符
spring·http
2301_780789665 小时前
UDP和TCP的主要区别是什么
服务器·网络协议·web安全·网络安全·udp
_丿丨丨_6 小时前
XSS(跨站脚本攻击)
前端·网络·xss
一只栖枝7 小时前
HCIA-Security 认证精讲!网络安全理论与实战全掌握
网络·web安全·网络安全·智能路由器·hcia·it·hcia-security
FileLink跨网文件交换7 小时前
文件摆渡系统十大软件|文件摆渡系统如何构建网络安全呢?
网络
晨欣10 小时前
大型语言模型(LLM)在网络安全中最具商业价值的应用场景(Grok3 回答 DeepSearch模式)
网络·web安全·语言模型
有书Show10 小时前
个人IP的塑造方向有哪些?
网络·网络协议·tcp/ip
HHRL-yx11 小时前
C++网络编程 5.TCP套接字(socket)通信进阶-基于多线程的TCP多客户端通信
网络·c++·tcp/ip