關於.NET(C#)裏使用HttpWebRequest中碰到的一些和Keep-Alive相關的內容 HTTP Keep-Alive詳解[轉]

c#採集其他網站數據時,會比較多的使用HttpWebRequest來實現HTTP訪問,讀取網站內容。

最近關注一下幾個問題:

  1. HttpWebRequest.ServicePoint
  2. ServicePointManager
  3. request.KeepAlive
  4. ServicePoint.SetTcpKeepAlive
  5. ServicePoint.ConnectionLimit
  6. ServicePoint.MaxIdleTime
  7. ServicePointManager.MaxServicePointIdleTime
  8. ServicePoint.ConnectionLeaseTimeout

一、ServicePoint:

  每個請求背後都有一個ServicePoint,可以把ServicePoint想象成請求背後的TCP連接對象,通過設置ServicePoint的相關屬性,可以控制TCP連接的一些行爲。

 

二、ServicePointManager

  顧名思義,這個是對 ServicePoint 進行管理的類,設置ServicePointManager的一些屬性,就可以控制ServicePoint默認的一些屬性,比如下面出現的Tcp KeepAlive,Connection Limit等等。

 

三、request.KeepAlive

  request.KeepAlive這個bool類型KeepAlive,是對Http請求的KeepAlive的控制,不是對TCP的KeepAlive。可以參考:

    HTTP Keep-Alive詳解[轉]  

    HTTP協議Keep-Alive模式詳解和HTTP頭字段總結 

 四、ServicePoint.SetTcpKeepAlive

  ServicePoint的SetTcpKeepAlive是設置TCP連接的KeepAlive特性,三個參數SetTcpKeepAlive(bool enabled, int keepAliveTime, int keepAliveInterval)的意思分別是:是否啓用TCP的KeepAlive。關於TCP的Keep-Alive可以參考這個文章:UNIX網絡編程——socket的keep-alive 

 

五、ConnectionLimit

  ServicePoint.ConnectionLimit和ServicePointManager.DefaultConnectionLimit都可以設置對某個URI資源可以同時訪問的最大數量。HTTP協議規範裏說,一個用戶最多可以同時建立兩個HTTP連接,如果大量線程同時請求一個站點,可能會受到限制。ConnectionLimit在Windows 10、Windows Server 2008 R2、Windows7 裏默認限制是2。修過修改ConnectionLimit應該可以允許更多的請求同時進行。

 

六、MaxIdleTime

  

 

附1:

.NET的 HttpWebRequest 設置KeepAlive時,有一個問題,就是隻有第一次發送出去的請求是帶有KeepAlive標頭的,後續的請求沒有KeepAlive標頭,解決這個問題的方式,是使用反射。

例如:

1 //.Net Framework 存在設置 HTTP Keep-Alive的BUG,每域名只有第一次請求Keep-Alive標頭存在,後續請求需要靠此代碼修正
2             var sp = request.ServicePoint;
3             var prop = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
4             prop.SetValue(sp, (byte)0, null);

這樣設置之後,每次請求都可以發送KeepAlive標頭。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章