2014-02-08 37 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); 

    }