Using HttpWebRequest, Keep-alive not working for many similar requests to localhost

醉酒当歌 提交于 2019-12-23 05:34:15

问题


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?


回答1:


Try response.Dispose(); instead of response.Close();



来源:https://stackoverflow.com/questions/24142664/using-httpwebrequest-keep-alive-not-working-for-many-similar-requests-to-localh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!