gpt4 book ai didi

.net-core - .Net Core HttpClient可以实现Http/2复用吗?

转载 作者:行者123 更新时间:2023-12-03 03:55:41 32 4
gpt4 key购买 nike

摘要

Http/2 协议(protocol)提供了通过单个连接复用多个请求的能力。这允许更有效地使用连接 - 请参阅https://http2.github.io/faq/#why-is-http2-multiplexed

我希望能够使用 .Net Core HttpClient 来实现这一点。然而,我的测试(基于以下内容)表明,请求与 TCP 连接的比例为 1:1。

.Net Core HttpClient 是否支持多路复用?如果是的话,它是如何实现的?

到目前为止的工作

我有一个示例应用程序(可以在 here 找到存储库,并使用以下代码;

using (var httpClient = new HttpClient())
{
var request1 = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com");
request1.Version = new Version(2, 0);

var request2 = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com");
request2.Version = new Version(2, 0);

var task1 = httpClient.SendAsync(request1);
var task2 = httpClient.SendAsync(request2);

Task.WaitAll(task1, task2);

var response1 = task1.Result;
var response2 = task2.Result;

Console.WriteLine($"Response 1 - Http Version: {response1.Version}, Http Status Code: {response1.StatusCode}");
Console.WriteLine($"Response 2 - Http Version: {response2.Version}, Http Status Code: {response2.StatusCode}");
}

这段代码产生以下结果(所以我知道正在使用 Http/2);

Response 1 - Http Version: 2.0, Http Status Code: OK
Response 2 - Http Version: 2.0, Http Status Code: OK

我可以从 Wireshark 看到已创建 2 个连接 - 每个连接都必须经过 TLS 设置;

Wireshark Capture

如果 HttpClient 多路复用请求,我希望看到单个连接(1 个端口、1 次握手等)。

最佳答案

我的代码的问题是 HttpClient 正在接收 request2在它有机会为 request1 创建 TCP 连接之前。因此,至HttpClient就目前而言,不存在可进行多路复用的现有连接。

但是,如果我创建一个初始请求(下面的 request0)并允许 HttpClient打开连接,然后后续请求(1 和 2)使用该现有连接。

代码:

using (var httpClient = new HttpClient())
{
// Setup first connection
var request0 = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com");
request0.Version = new Version(2, 0);

var task0 = httpClient.SendAsync(request0);
var response0 = task0.Result;

Console.WriteLine($"Response 0 - Http Version: {response0.Version}, Http Status Code: {response0.StatusCode}");

// Now send the multiplexed requests
var request1 = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com");
request1.Version = new Version(2, 0);

var request2 = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com");
request2.Version = new Version(2, 0);

var task1 = httpClient.SendAsync(request1);
var task2 = httpClient.SendAsync(request2);

Task.WaitAll(task1, task2);

var response1 = task1.Result;
var response2 = task2.Result;

Console.WriteLine($"Response 1 - Http Version: {response1.Version}, Http Status Code: {response1.StatusCode}");
Console.WriteLine($"Response 2 - Http Version: {response2.Version}, Http Status Code: {response2.StatusCode}");
}

以及 Wireshark 证明(仅 1 个端口,1 次握手):

Wireshark capture

关于.net-core - .Net Core HttpClient可以实现Http/2复用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47830834/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com