2014-02-08 96 views
0

我做了這個TCP客戶端,但是在獲取響應時遇到問題。它執着在47行從TCP客戶端獲取響應

var line = sr.ReadLine(); 

但有時它把響應登錄盒和棍棒再次行24

void log(string x) 
     { 
      richTextBox1.Text += x + Environment.NewLine; 
     } 

下面是代碼:https://app.box.com/s/7ly47ukztlo5eta3wqbk

如何解決呢?

+1

你想完全解決什麼問題? – Leo

+0

它在「ReadLine()」中「粘住」,因爲該操作會阻塞,直到它遇到換行符,這可能不會被髮送或接收。 – CodeCaster

回答

1

您必須先從TcpClient獲取網絡流。之後開始閱讀。

使用下面的代碼。

TcpClient tcpClient = new TcpClient(); 

// Uses the GetStream public method to return the NetworkStream. 
NetworkStream netStream = tcpClient.GetStream(); 

if (netStream.CanRead) 
    { 
     // Reads NetworkStream into a byte buffer. 
     byte[] bytes = new byte[tcpClient.ReceiveBufferSize]; 

     // Read can return anything from 0 to numBytesToRead. 
     // This method blocks until at least one byte is read. 
     netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize); 

     // Returns the data received from the host to the console. 
     string returndata = Encoding.UTF8.GetString (bytes); 

     Console.WriteLine ("This is what the host returned to you: " + returndata); 

    } 
相關問題