2010-07-05 625 views
0

好的。這是完整的代碼。我試圖重新使用連接設置KeepAlive,但它不起作用。我使用Feedler和Charles查看了Http消息,但我只能看到Connection:關閉響應。C#不能重用Http連接。沒有KeepAlive頭。 HttpWebRequest.KeepAlive = true;

我看到600個TCP連接處於等待狀態,由10個線程打開。每個線程一次運行一個http請求。

還有一堆反應說 - 未經驗證的請求。該服務需要摘要式身份驗證。代碼顯然是靜態的,只需從不同的線程運行相同的請求幾百次...那麼爲什麼有些請求無法被認證? 我

static void GetRest(string rest) 
    { 
     int i = Interlocked.Increment(ref counter); 

     Uri uri = new Uri(rest); 
     CredentialCache cc = new CredentialCache(); 
     cc.Add(uri, "Digest", new NetworkCredential("zz", "zz")); 

     ServicePointManager.FindServicePoint(uri).SetTcpKeepAlive(true, 6000000, 100000); 
     ServicePointManager.FindServicePoint(uri).ConnectionLimit = 5; 

     while (!stop) 
     { 

      HttpWebRequest req = WebRequest.Create(rest) as HttpWebRequest; 

      req.Credentials = cc; 
      req.Method = "GET"; 
      req.Timeout = timeout; 
      req.KeepAlive = true; 

      try 
      { 
       using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) 
       { 
        StreamReader sr = new StreamReader(res.GetResponseStream()); 

        string result = sr.ReadToEnd().Substring(0, 20); 
        int rc = Interlocked.Increment(ref responseCounter); 
        Console.Write("."); 

        Thread.Sleep(20); 
       } 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("EXCEPTION {0}, {1}", i, ex.Message); 
       Interlocked.Increment(ref badResponseCounter); 
      } 
     } 

     Interlocked.Decrement(ref counter); 
    } 
+0

我不能給太多瞭解您的具體問題,但對於這樣的事情,我肯定會建議把它歸結爲一個「最低工作示例」,然後從那裏建立起來。例如:首先嚐試1個經過驗證的HTTP請求到這個URI。暫時沒有「ServicePointManager」的東西。然後嘗試串聯600個(不平行)。也許在這一點上'ServicePointManager'的東西需要回來。然後嘗試10並行。等等。 – Domenic 2010-07-05 21:40:14

+0

這個問題也似乎與你自己的相關:http://stackoverflow.com/questions/2179626/reuse-a-httpwebrequest – Domenic 2010-07-05 21:41:51

+0

Domenic。謝謝,但在另一個線程的建議說 - 關閉我做的Httpresponse - 我使用它... ServicePoint的東西是必要的。沒有它,整個事情工作x3慢 – 2010-07-05 21:51:48

回答

1

如果你看到連接:關閉的響應,這難道不是指示你該服務器迫使連接每個請求後關閉。我不確定在這一點上你可以做些什麼來改變這種行爲。也許你可以問服務提供商他們爲什麼要返回連接:在每個響應中關閉。

+0

我會問。但我是所有這些HTTP的新手。你確定這是服務器工作嗎?我在我的請求中看不到Keep-Alive標題...可能是因爲我的客戶端代碼沒有要求它保持活動狀態,因此請求關閉。看看這裏:http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/87bc7029-ce23-438a-a767-f7c32dcc63a7 *認證請求*不會被重複使用!我嘗試UseunsafeAuthenticatedConnectionSharing = true,但它沒有奏效。該線程是從2005年開始的。 – 2010-07-06 02:06:34

0

我有這樣的走了後,我設置request.UnsafeAuthenticatedConnectionSharing =真和 ServicePointManager.MaxServicePointIdleTime = 100000類似的問題; //不能爲0