问题
I developing a bidirection dialog between a server and a device using a telnet connection. I would like to wait and get the read buffer before sending the next command. I tryed to use this:
TcpClient tcpClient;
NetworkStream networkStream;
StreamWriter streamWriter;
tcpClient = new TcpClient("10.0.0.51", 23);
networkStream = tcpClient.GetStream();
StreamReader streamReader = new StreamReader(networkStream);
networkStream.ReadTimeout = 500;
while(wline!="exit"){
Console.Write(streamReader.ReadToEnd());
Console.Write("next command:");
wline =Console.ReadLine();
streamWriter.Write(wline);
}
but seems that ReadToEnd() doesn't work properly. If I use Read() (single byte) I could receive something.
回答1:
ReadToEnd reads everything until the end of the stream, which in the case of a network tream, occurs when that stream closes. Unless the device on the other end closes the stream, there is no way for your client to know that there are indeed no more data to read.
You should use ReadLine to read and process one line at a time, or use ReadBlock to read the data in blocks.
来源:https://stackoverflow.com/questions/17216943/tcpclient-stream-streamreader-readtoend-for-telnet