2012-05-27 82 views
1

我使用HttpWebRequest的方式,你的意思是:處理響應,當我完成它,希望這將使它重用任何可用的TCP連接,但它doesn 't:收到響應後關閉連接。我看到這發生在我使用TCPView時。HttpWebRequest - 重用TCP連接

這裏是我的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屬性默認爲真,因爲是HttpWebRequest.Pipelines。那麼我做錯了什麼?

謝謝!

回答

2

事實證明,我正在擊中HttpWebRequest尊重的「每個主機2個併發連接」規則。

解決的辦法是設置此靜態屬性:

System.Net.ServicePointManager.DefaultConnectionLimit = 15; 

排序:)