When I use only \r
as a line terminator, the StreamReader.ReadLine()
method doesn't work. It works if I use Environment.NewLine
, \r\n
or \ra
("a" being any character). Is this a bug? The same problem doesn't occurs when using MemoryStream instead of NetworkStream. What workarounds can I use if I can't change the protocol?
My service
Thread service = new Thread((ThreadStart)delegate
{
TcpListener listener = new TcpListener(IPAddress.Loopback, 2051);
listener.Start();
using (TcpClient client = listener.AcceptTcpClient())
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
string inputLine = reader.ReadLine(); // doesn't work - freezes here
writer.Write("something\r");
}
});
service.Start();
My client
using (TcpClient client = new TcpClient("localhost", 2051))
using (NetworkStream stream = client.GetStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader = new StreamReader(stream))
{
writer.AutoFlush = true;
writer.Write("something else\r");
var message = reader.ReadLine(); // doesn't work even
// if I remove the freezing point above
}
I solved the problem with my own ReadLine method
public static class StreamReaderExtensions
{
public static string ReadLineSingleBreak(this StreamReader self)
{
StringBuilder currentLine = new StringBuilder();
int i;
char c;
while ((i = self.Read()) >= 0)
{
c = (char)i;
if (c == '\r'
|| c == '\n')
{
break;
}
currentLine.Append(c);
}
return currentLine.ToString();
}
}
来源:https://stackoverflow.com/questions/8387536/streamreader-readline-not-working-over-tcp-when-using-r-as-line-terminator