我使用HttpWebRequest
向localhost上的相同HTTP网址发送了许多同步请求,我需要重新使用TCP连接防止短暂的港口耗尽。
但我似乎无法让Keep-alive工作。
这是我发出HTTP请求的代码:
var request = (HttpWebRequest) WebRequest.Create(url);
HttpWebResponse response = null;
request.Method = "GET";
request.KeepAlive = true;
try
{
response = (HttpWebResponse) request.GetResponse();
// ...
}
catch (Exception e)
{
// ...
}
finally
{
if (response != null)
{
response.Close();
}
}
我在循环中多次调用上面的代码。所有请求都成功,并返回OK状态代码(200),但是运行netstat -ano
显示TIME_WAIT
状态中存在多个MANY连接,我希望它可以重新使用单个连接。< / p>
我尝试在localhost(默认的ASP.NET MVC应用程序)和WebLogic应用程序上调用IIS Express服务器,结果相同。
我还尝试了.NET 4.5中的HttpClient
。
这很快就会导致短暂的端口耗尽。
我在做什么有什么不对吗?如何让.NET重用TCP连接?