使用 \r 作为行终止符时,StreamReader.ReadLine 无法通过 TCP 工作
当我仅使用 \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
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我用自己的ReadLine方法解决了这个问题
I solved the problem with my own ReadLine method