2010-07-05 103 views
3

我使用的TcpClient下面的代碼TCPClient似乎不維持保持連接狀態,爲什麼?

byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("username" + ":" + "password"); 
     string follow = "track=soccer,twitter"; 
     byte[] encode_follow = System.Text.Encoding.UTF8.GetBytes(follow); 

     using (TcpClient client = new TcpClient()) 
     { 
      string requestString = "POST /1/statuses/filter.json HTTP/1.1\r\n"; 
      requestString += "Host: stream.twitter.com\r\n"; 
      requestString += "User-Agent: www.site.com\r\n"; 
      requestString += "Referer: http://www.site.com\r\n"; 
      requestString += "Content-Type: application/x-www-form-urlencoded\r\n"; 
      requestString += "Authorization: " + "Basic " + Convert.ToBase64String(encbuff) + "\r\n"; 
      requestString += "Content-length: " + follow.Length + "\r\n"; 
      requestString += "Connection: keep-alive\r\n"; 
      requestString += "\r\n"; 
      requestString += follow; 
      requestString += "\r\n\r\n"; 

      client.Connect("stream.twitter.com", 80); 
      //client.ReceiveTimeout = 100; 
      using (NetworkStream stream = client.GetStream()) 
      { 
       // Send the request. 
       StreamWriter writer = new StreamWriter(stream); 
       writer.Write(requestString); 
       writer.Flush(); 

       // Process the response. 

        StreamReader rdr = new StreamReader(stream); 

        while (!rdr.EndOfStream) 
        { 
         Console.WriteLine(rdr.ReadLine()); 
         Console.WriteLine("IS end: " + rdr.EndOfStream.ToString()); 
        } 
       } 

     } 

會發生什麼事是,雖然Console.WriteLine命令(rdr.ReadLine());行會打印出幾秒鐘的狀態,而不是停止+不再觸及斷點,即使它仍然連接。

什麼應該做的是繼續寫狀態的控制檯,因爲它是一個保持活動連接和「推特」關鍵字獲取每隔幾秒鐘不斷提過幾次。

任何想法可能會造成這個問題?

+0

對於HTTP協議使用'TcpClient'似乎是一種矯枉過正。你有沒有考慮過使用「WebClient」? – 2010-07-05 18:44:23

+0

那麼,當我使用帶keepalive連接的webclient或httpwebrequest時,流會在一段時間後關閉,我必須關閉連接並重新打開。我認爲TcpClient是唯一支持保持連接打開並無限期地從流中讀取數據的程序。 – rksprst 2010-07-05 18:48:57

+0

我使用WebClient成功閱讀Twitter提要。我使用WebClient.OpenReadAsync並使用StreamReader讀取。到目前爲止,我還沒有注意到自己的連接已經關閉。 – dtb 2010-07-05 18:54:26

回答

0

檢查了這一點:

public class Program 
{ 
    public static void Main() 
    { 
     using (var client = new WebClient()) 
     { 
      client.Credentials = new NetworkCredential("username", "password"); 
      client.OpenReadCompleted += (sender, e) => 
      { 
       using (var reader = new StreamReader(e.Result)) 
       { 
        while (!reader.EndOfStream) 
        { 
         // TODO: feed this to your favorite JSON parser 
         Console.WriteLine(reader.ReadLine()); 
        } 
       } 
      }; 
      client.OpenReadAsync(new Uri("http://stream.twitter.com/1/statuses/filter.json?track=soccer,twitter")); 
     } 
     Console.ReadLine(); 
    } 
} 

應該讓事情變得更容易。

+0

謝謝,你的代碼實際上有同樣的問題 - 這是我怎麼弄清楚什麼是錯的。原來,這是一個帳戶的流權限問題。我嘗試了另一個帳戶,它很好。 – rksprst 2010-07-06 03:06:01

+0

你能詳細說明你的流媒體權限是什麼意思嗎? – jpierson 2013-01-10 19:27:57

相關問題