BufferedStream & StreamReader
-
I have some code that reads from a NetworkStream, retrieving both standard strings as well as binary data. The following code works:
connection_ = new TcpClient(host, port);
connection_.ReceiveTimeout = 30000;stream_ = connection_.GetStream();
bufStream_ = new BufferedStream(stream_);reader_ = new StreamReader(stream_, Encoding.GetEncoding("iso-8859-1"));
string str = reader_.ReadLine();
byte b = (byte)bufStream_.ReadByte();
But it's a little weird because the reader goes directly against the network stream for reading full lines as strings, but it goes through the buffered stream when reading individual bytes. Even though this works, I tried the following change:
reader_ = new StreamReader(bufStream_, Encoding.GetEncoding("iso-8859-1"));
But this doesn't work at all. When it gets to the ReadLine, it blocks indefinitely. Could this be a bug in BufferedStream? I'm using .Net 1.0, by the way.
-
I have some code that reads from a NetworkStream, retrieving both standard strings as well as binary data. The following code works:
connection_ = new TcpClient(host, port);
connection_.ReceiveTimeout = 30000;stream_ = connection_.GetStream();
bufStream_ = new BufferedStream(stream_);reader_ = new StreamReader(stream_, Encoding.GetEncoding("iso-8859-1"));
string str = reader_.ReadLine();
byte b = (byte)bufStream_.ReadByte();
But it's a little weird because the reader goes directly against the network stream for reading full lines as strings, but it goes through the buffered stream when reading individual bytes. Even though this works, I tried the following change:
reader_ = new StreamReader(bufStream_, Encoding.GetEncoding("iso-8859-1"));
But this doesn't work at all. When it gets to the ReadLine, it blocks indefinitely. Could this be a bug in BufferedStream? I'm using .Net 1.0, by the way.
I got around this problem by writing my own "ReadLine" for the buffered stream, eliminating the need for the StreamReader. Here it is, if you are interested. Please excuse the use of "goto", but it was the most natural (and efficient) way to write the code:
/// Gets the next line of text from the NTTP server. Reads from the /// buffered stream one byte at a time, until the characters \r \n /// have been encountered. Returns the text string, without the /// line terminators. private string ReadLine() { StringBuilder sb = new StringBuilder(); byte b; // Read bytes until the \r is encountered, adding it to the string. p0: b = (byte)bufStream_.ReadByte(); if (b != '\r') { sb.Append((char)b); goto p0; } // At this point, the \r has been seen, so we're looking for the // \n. If a second \r is encountered, loop back and look for \n // again. If any other character is found, add it to the string // and start over. p1: b = (byte)bufStream_.ReadByte(); if (b != '\n') { sb.Append((char)'\r'); if (b == '\r') { goto p1; } else { sb.Append((char)b); goto p0; } } return sb.ToString(); }