作者:LinerContourMakeup_669 | 来源:互联网 | 2023-01-04 20:30
我想我有答案(虽然肯定会重视反馈);
上面代码的问题是HttpClient正在接收request2,因为它有机会为request1创建TCP连接.因此,就HttpClient而言,没有与Multiplex的现有连接.
但是,如果我创建了一个初始请求(下面的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次握手):
我将继续进行进一步的研究,但这似乎是一个胜利者.如上所述,任何反馈都非常赞赏.
1> Mark Taylor..:
我想我有答案(虽然肯定会重视反馈);
上面代码的问题是HttpClient正在接收request2,因为它有机会为request1创建TCP连接.因此,就HttpClient而言,没有与Multiplex的现有连接.
但是,如果我创建了一个初始请求(下面的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次握手):
我将继续进行进一步的研究,但这似乎是一个胜利者.如上所述,任何反馈都非常赞赏.
限制MaxConnectionsPerServer也会强制进行多路复用.默认值为2147483647.`var handler = new WinHttpHander(); handler.MaxCOnnectionsPerServer= 1; var httpClient = new HttpClient(handler);`