如何避免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();
}
相关推荐
Orange_sparkle5 小时前
Pi Agent vs LangGraph:从人机交互、企业 RAG 到持久化工作流的完整选型指南
java·网络·人机交互
右耳朵猫AI5 小时前
Go周刊2026W36 | Go 1.27.1 发布、TinyGo 0.42、HTTP/2 原生迁入 net/http、quic-go 0.62
redis·http·golang
xiaoye-duck6 小时前
《Linux 网络编程》深入传输层 UDP 协议原理:端口、报文、缓冲区与内核源码解析
linux·网络·udp
好评1246 小时前
【Linux】数据链路层
linux·运维·网络
天衍四九-6 小时前
第一章:从 LLM 到 Agent —— DeepSeek Harness 入门
网络·数据库·人工智能·python
Jae den6 小时前
网络丢包是什么?
网络
XR1234567888 小时前
医院无线整网高密覆盖选型深度解析
运维·网络
发量惊人的中年网工8 小时前
企业一体化安全网关选型:适用规模、需求架构与实施建议
网络
取啥都被占用8 小时前
两个网络供应商靠树莓派跨个域
网络·树莓派
是个西兰花10 小时前
网络基础1
linux·网络·c++·智能路由器