使用HttpWebRequest,Keep-alive不适用于对localhost的许多类似请求 [英] Using HttpWebRequest, Keep-alive not working for many similar requests to localhost
问题描述
我正在使用 HttpWebRequest
向localhost上的相同HTTP网址发送许多同步请求,而我需要重新使用TCP连接以防止短暂的端口耗尽。
但我似乎无法使Keep-alive正常工作。
这是我发出HTTP请求的代码:
var request =(HttpWebRequest)WebRequest .Create(URL);
HttpWebResponse response = null;
request.Method =GET;
request.KeepAlive = true;
尝试
{
response =(HttpWebResponse)request.GetResponse();
// ... ...
}
catch(例外e)
{
// ...
}
最后
{
if(response!= null)
{
response.Close();
}
}
我在循环中多次调用上面的代码。所有请求都成功,并返回OK状态代码(200),但运行 netstat -ano
显示 TIME_WAIT中有多个很多连接
state,我希望它可以重新使用单个连接。
我尝试在localhost上调用两个IIS Express服务器(默认ASP.NET MVC)应用程序)和WebLogic应用程序,结果相同。
我还尝试从.NET 4.5中 HttpClient
。 / p>
这很快就会导致短暂的端口耗尽。
我正在做什么有什么问题?如何让.NET重用TCP连接?
尝试response.Dispose();而不是response.Close();
I'm using HttpWebRequest
to send many sync requests to the same HTTP URL on localhost, and I need to re-use TCP connections to prevent ephemeral port depletion.
But I don't seem to be able to get Keep-alive working.
Here's my code where I make the HTTP request:
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();
}
}
I call the above code many times in a loop. All requests are successful, and return OK status code (200), but running netstat -ano
reveals that there are MANY MANY connections in the TIME_WAIT
state, where I expect it to re-use a single connection.
I tried calling both an IIS Express server on localhost (default ASP.NET MVC application) and a WebLogic application, with the same result.
I also tried HttpClient
from .NET 4.5.
This quickly results in running out of ephemeral ports.
Is there anything wrong with what I'm doing? How can I make .NET re-use TCP connections?
Try response.Dispose(); instead of response.Close();
这篇关于使用HttpWebRequest,Keep-alive不适用于对localhost的许多类似请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!