2011-04-30 56 views
1

我需要從服務器應用程序接收第二個答覆。當我第一次連接到服務器應用程序時,我收到了答覆。但是當我嘗試發送另一條消息時,我無法收到它。使用TcpClient和StreamReader不能接收多條消息

我試過尋找解決方案,但找不到任何東西。我相信問題是我的讀者指針仍然是最後的。這就是爲什麼我無法閱讀下一個答覆。這裏是我的代碼:

public static void XConn() 
{ 
    TcpClient client = new TcpClient(); 
    client.Connect("xxx.xxx.xxx.xxx",xx); // i cant show the IP sorry 
    Stream s = client.GetStream(); 
    StreamReader sr = new StreamReader(s); 
    StreamWriter sw = new StreamWriter(s); 

    String r = ""; 
    sw.AutoFlush = true;  

    sw.WriteLine("CONNECT\nlogin:xxxxxxx \npasscode:xxxxxxx \n\n" + Convert.ToChar(0)); // cant show also 

    while(sr.Peek() >= 0) 
    { 
     r = sr.ReadLine(); 
     Console.WriteLine(r); 
     Debug.WriteLine(r); 
     if (r.ToString() == "") 
      break; 
    } 

    sr.DiscardBufferedData(); 

    //get data needed, sendMsg is a string containing the message i want to send 
    GetmsgType("1"); 
    sw.WriteLine(sendMsg); 

    // here i try to receive again the 2nd message but it fails =(
    while(sr.Peek() >= 0) 
    { 
     r = sr.ReadLine(); 
     Console.WriteLine(r); 
     Debug.WriteLine(r); 
     if (r.ToString() == "") 
      break; 
    } 

    s.Close(); 

    Console.WriteLine("ok"); 
} 
+0

哪種協議是這樣嗎? – 2011-04-30 06:16:00

+0

協議?你什麼意思?你的意思是發送的消息? – 2011-04-30 06:25:26

+0

是 - 發送和接收的消息的指定格式是什麼?它應該是CONNECT \ n登錄... \ n密碼... \ n \ n \ 0?此外,它是如何失敗 - 你是否得到一個錯誤或沒有被打印出來? – 2011-04-30 06:30:13

回答

0

TcpClient.GetStream()返回NetworkStream,它不支持查找,所以你不能改變讀者指針,只要連接是打開的,它從來沒有真正的結束,無論是。這意味着StreamReader.Peek()方法可能會返回一個令人誤解的-1,當服務器在響應之間存在延遲時。

得到響應的一個可靠方法是設置讀取超時並保持循環,直到引發異常,您可以捕獲並繼續執行。該流仍然可以發送另一條消息。

 s.ReadTimeout = 1000; 

     try 
     { 
      sw.WriteLine(sendMsg); 

      while(true) 
      { 
      r = sr.ReadLine(); 
      Console.WriteLine(r); 
      } 

     sr.DiscardBufferedData(); 
     } 
     catch(IOException) 
     { 
     //Timed out—probably no more to read 
     } 


UPDATE:以下也可工作,在這種情況下,你並不需要擔心設置超時或捕獲異常:

  while(true) 
     { 
      r = sr.ReadLine(); 
      Console.WriteLine(r); 
      if (sr.Peek() < 0) break; 
     } 
+0

虐待這位先生。生病後會給你一個反饋。謝謝你的解釋..我之所以有這樣一種協議,是因爲它需要一個STOMP。即時連接到它之一..首先,當我嘗試連接,然後訂閱它回覆的消息..然後像我上面發佈的代碼..當我嘗試發送消息(例如即時通訊獲取名稱列表) ,我的代碼只是停止這部分代碼... r = sr.ReadLine(); – 2011-04-30 08:27:12