使用\ r作为行终止符时,StreamReader.ReadLine无法通过TCP工作

时间:2011-12-05 15:19:18

标签: c# .net streamreader readline networkstream

当我仅使用\r作为行终止符时,StreamReader.ReadLine()方法不起作用。如果我使用Environment.NewLine\r\n\ra(“a”是任何字符),它都有效。这是一个错误吗?使用MemoryStream而不是NetworkStream时不会发生同样的问题。如果我无法更改协议,我可以使用哪些变通方法?

我的服务

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();

我的客户

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 个答案:

答案 0 :(得分:7)

我用自己的ReadLine方法解决了这个问题

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();
    }
}

答案 1 :(得分:0)

我认为您应该使用\n作为换行符。