c# - HttpClient 连接状态在使用一段时间后保持在 TIME_WAIT 导致套接字异常

标签 c# asp.net-mvc websocket asp.net-web-api2 dotnet-httpclient

我们正在使用 HttpClient 访问托管在另一台服务器上的 WebAPI。 我们有一个 MVC5 应用程序,它从 WebAPI window server 2012 R2 with IIS 8.5 获取数据

下面是从webapi获取数据的代码

//creating static instance of http client
private static HttpClient client = new HttpClient();

//static method to add common header
static ApiCall()
{
   client.DefaultRequestHeaders.Add("Authorization", 
                 string.Format("Value {0}", AppSettings.ApiSecurityKey));
   client.DefaultRequestHeaders.ConnectionClose = true;
}

//finally posting data to the api
//objprop contains the data and other setting
string url = "apiurl";
var postContent = new StringContent(objprop.DataForPost, 
      System.Text.Encoding.UTF8, objprop.ContentType);
response = client.PostAsync(url, postContent).Result;

但是在 PT 测试期间,我收到了多个处于 TIME_WAIT 状态的请求。因此,我们收到套接字异常。

使用 HttpClient 的最佳做法是什么?

有没有什么设置可以在使用后释放套接字。

类似的问题在这里
1. How do I prevent Socket/Port Exhaustion?
2. Why does HttpClient leave sockets open?
但这对我没有帮助。

编辑 1 更多细节

: InnerException- System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted x.x.x:80 at System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult) at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- End of inner exception stack trace --- : URL- http://x.x.x.com//api/GetMenu

最佳答案

您对HttpClient 的使用是正确的;尽管正如某些人评论的那样,一直使用 async 会更好,但这不是导致错误的原因。

TIME_WAIT是 TCP/IP 连接的强制阶段;建立连接后,发起连接关闭的一方将在预先配置的时间内进入此状态。

TCP/IP 有一个有限的端口池用于进出连接。

新连接使用其中的一个子集(也称为动态或临时端口范围)在每一侧分配一个端口。

您的应用在尝试创建新的传出连接时收到错误“地址正在使用”,但 TCP 已用完动态范围内的本地端口。

根据哪一端发起连接关闭,可能是您的客户端或服务器用完了端口。

This article from Microsoft详细说明如何修改 Windows TCP/IP 设置以获得高连接率:

  • TIME_WAIT 时间从 120 秒更改为 30 秒
  • 将动态端口数从 16384 增加到 64511

同时执行这两项操作会将最大连接速率从 136 个连接/秒增加到大约 2150 个。

关于c# - HttpClient 连接状态在使用一段时间后保持在 TIME_WAIT 导致套接字异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55983303/

相关文章:

c# - CLR 托管 : Call a function with an arbitrary method signature?

javascript - 为什么 JavaScript 中带小数的最大位数只有 16

javascript - 意外的响应代码 426

Node.js WebSockets 发送消息

javascript - 在文件之间从 socket.io 共享服务器

c# - 适当使用自定义属性?

C# 将 ttf 和 otf 转换为 eot 文件

c# - 是否有可能在最小化的应用程序中运行 UWP WebView,包括声音输出?

c# - Asp.net MVC 2 缓存

c# - 在带有 HtmlAttributes 的 MVC Html.ActionLink 上使用 @class 和自定义类失败