我使用的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());行會打印出幾秒鐘的狀態,而不是停止+不再觸及斷點,即使它仍然連接。
什麼應該做的是繼續寫狀態的控制檯,因爲它是一個保持活動連接和「推特」關鍵字獲取每隔幾秒鐘不斷提過幾次。
任何想法可能會造成這個問題?
對於HTTP協議使用'TcpClient'似乎是一種矯枉過正。你有沒有考慮過使用「WebClient」? – 2010-07-05 18:44:23
那麼,當我使用帶keepalive連接的webclient或httpwebrequest時,流會在一段時間後關閉,我必須關閉連接並重新打開。我認爲TcpClient是唯一支持保持連接打開並無限期地從流中讀取數據的程序。 – rksprst 2010-07-05 18:48:57
我使用WebClient成功閱讀Twitter提要。我使用WebClient.OpenReadAsync並使用StreamReader讀取。到目前爲止,我還沒有注意到自己的連接已經關閉。 – dtb 2010-07-05 18:54:26