StreamReader.当使用 作为行结束符时,ReadLine不能在TCP上工作

本文关键字:不能 ReadLine TCP 工作 结束 StreamReader | 更新日期: 2023-09-27 18:16:46

当我仅使用'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
}

StreamReader.当使用
作为行结束符时,ReadLine不能在TCP上工作

我用自己的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();
    }
}