HttpWebRequest - 重用TCP连接

时间:2012-05-27 22:13:22

标签: tcp httpwebrequest connection

我使用HttpWebRequest的方式是你的意思:当我完成它时,处理响应,希望这会使它重用任何可用的TCP连接,但是不会:收到响应后关闭连接。我在使用TCPView时看到了这种情况。

这是我的HttpWebRequest代码:

 private HttpWebResponse ExecuteRequest(String baseRelativeUri, String method, Ds postValues) {

        /////////////////////////////////////////
        // Set-up

        Uri uri = new Uri( _baseUri, baseRelativeUri );

        _cookies.ProcessDomains();

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( uri );
        request.CookieContainer = _cookies;
        request.Method          = method;
        request.UserAgent       = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0";

        if( postValues != null ) SetPostContent( request, postValues );

        /////////////////////////////////////////
        // Response

        return (HttpWebResponse)request.GetResponse();
    }

    protected HtmlDocument ExecuteRequestHtml(String baseRelativeUri, String method, Ds postValues, HttpStatusCode expectedStatusCode) {

        using(HttpWebResponse response = ExecuteRequest(baseRelativeUri, method, postValues)) {

            if( response.StatusCode != expectedStatusCode ) throw new WebException("Did not receive " + expectedStatusCode + " response.");

            /////////////////////////////////////////
            // HtmlDocument

            using(Stream stream = response.GetResponseStream()) {

                HtmlDocument doc = new HtmlDocument();
                doc.Load( stream );
                return doc;
            }
        }
    }

根据MSDN,HttpWebRequest.KeepAlive属性默认为true,HttpWebRequest.Pipelines也是如此。那么我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

事实证明我正在达到HttpWebRequest所尊重的“每个主机的2个同时连接”规则。

解决方案是设置此静态属性:

System.Net.ServicePointManager.DefaultConnectionLimit = 15;

排序:)