每个http请求需要60秒为什么?

问题描述 投票:0回答:1

下面的代码块说明了如何使用 TCP 和网络流发送 HTTP 请求。然而,无论应用任何过滤,每个请求始终平均消耗 60 秒。无论是单个数据还是一千个数据到达,延迟都保持不变。为什么会持续60秒?是否没有选项可以缩短此时间或设置立即获取数据而无需等待?

// Specify the server and port
string server = "xxx.com";
int port = 80;

// Specify the HTTP request
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\"}";

// Create a 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))
    {
        // Send the HTTP request
        await writer.WriteAsync(httpRequest);
        await writer.FlushAsync();

        // Read the response
        string response = await reader.ReadToEndAsync();

        // Display the response
        Console.WriteLine("Response: " + response);
    }
}

我不太熟悉这些旧方法。我尝试了 NoDelay() 和各种超时配置等策略,但没有一个被证明有效。

预先感谢您的协助。


在@jonskeet 的回答后进行编辑


// add `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\"}";

c# .net http tcp networkstream
1个回答
8
投票

我可以看到您所获得的特定代码存在两个问题,但更一般地说,我强烈鼓励您不要对 HTTP 请求使用

TcpClient
,除非您绝对必须。我相信,如果您使用
HttpClient
,这两个问题都可以避免。

首先,您指定了

Content-Length: 27
标头 - 但据我所知,您随后发送了 28 字节的内容。也许这只是示例代码中的一个问题,但它确实证明了这种方法是多么脆弱。

其次,你正在调用

StreamReader.ReadToEnd
,这意味着你正在等待连接关闭。您没有关闭连接,这意味着您希望服务器关闭它。但在 HTTP/1.1(这是您指定的版本)中,默认行为是保持连接处于活动状态。所以我强烈怀疑您所看到的是服务器立即发送响应 - 然后在一分钟后超时等待下一个请求。

为了避免这种情况,您可以发送

Connection: close
标头...或者最好使用
HttpClient
,这样您就不需要了解 HTTP 的详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.