You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何TCP发送HTTP请求每次耗时60秒?求优化方法

HTTP请求固定耗时60秒的原因及解决办法

我使用TCP和NetworkStream发送HTTP请求的代码示例如下,无论做何种过滤、数据量大小,每次请求平均耗时均为60秒,延迟始终固定。请问这是什么原因?有没有办法缩短耗时,或者设置为立即获取数据无需等待?

// 指定服务器和端口
string server = "xxx.com";
int port = 80;

// 指定HTTP请求内容
string httpRequest = "POST /ApiPrefixNameHere/ControllerNameHere/ActionNameHere HTTP/1.1\r\nHost: xxx.com\r\naccept: text/plain\r\nContent-Type: application/json-patch+json\r\nContent-Length: 27\r\n\r\n{\"ParameterNameHere\":\"1580\"}";

// 创建TcpClient
using (TcpClient tcpClient = new())
{
    await tcpClient.ConnectAsync(server, port);

    using (NetworkStream networkStream = tcpClient.GetStream())
    using (StreamWriter writer = new(networkStream, Encoding.ASCII))
    using (StreamReader reader = new(networkStream, Encoding.ASCII))
    {
        // 发送HTTP请求
        await writer.WriteAsync(httpRequest);
        await writer.FlushAsync();

        // 读取响应
        string response = await reader.ReadToEndAsync();

        // 显示响应内容
        Console.WriteLine("Response: " + response);
    }
}

我对这类较旧的网络通信方法不太熟悉,试过设置NoDelay()以及各类超时配置,但都没有效果。


解决方法:添加Connection: close请求头

问题根源在于HTTP 1.1默认采用**持久连接(Keep-Alive)**模式,服务器返回响应后不会主动关闭连接,而ReadToEndAsync()方法会一直等待到流关闭才会结束读取,最终触发连接超时(通常为60秒)才返回结果。

在请求头中添加Connection: close,明确告知服务器返回响应后立即关闭连接,这样ReadToEndAsync()读取完响应数据后就能及时返回,无需等待超时。修改后的请求内容如下:

// 添加 `Connection: close` 请求头
string httpRequest = "POST /ApiPrefixNameHere/ControllerNameHere/ActionNameHere HTTP/1.1\r\nHost: xxx.com\r\naccept: text/plain\r\nContent-Type: application/json-patch+json\r\nConnection: close\r\nContent-Length: 28\r\n\r\n{\"ParameterNameHere\":\"1580\"}";

注意:修改请求头后,Content-Length的值需要对应调整(示例中从27改为28),确保和实际请求体的字节数一致。


内容的提问来源于stack exchange,提问作者Emir Kılınç

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 09:52:36