StreamReader.ReadLine not working over TCP when us

2019-02-25 00:05发布

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
}

2条回答
ら.Afraid
2楼-- · 2019-02-25 00:58

I think you should be using \n as newline character instead.

查看更多
我想做一个坏孩纸
3楼-- · 2019-02-25 00:59

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();
    }
}
查看更多
登录 后发表回答