【问题标题】:StreamReader.ReadLine and CRStreamReader.ReadLine 和 CR
【发布时间】:2009-07-08 18:59:23
【问题描述】:

我在这里很密集吗? StreamReader.ReadLine 声明:

行定义为一系列字符后跟换行符 ("\n")、回车符 ("\r") 或回车符后紧跟换行符 ("\r\n" )

那么,为什么这没有按预期工作?

' Server
Dim tcpL as New TcpListener(IPAddress.Any, 5000)
tcpL.Start(1)
Using tcpC as TcpClient = tcpL.AcceptTcpClient(), _
s as NetworkStream = tcpC.GetStream(), _
sr as New StreamReader(s, System.Text.Encoding.ASCII, True)
   Dim message As String = sr.ReadLine()
   Console.WriteLine(message)
End Using
Console.ReadLine()

' Client
Using tcpC as New TcpClient()
  tcpC.Connect(IPAddress.Loopback, 5000)
  Using s as NetworkStream = tcpC.GetStream(), _
  sw as New StreamWriter(s, System.Text.Encoding.ASCII)
     sw.AutoFlush = True
     sw.Write("Hello there!")
     sw.Write(vbCR) ' Note the CR terminator
     Console.ReadLine()
  End Using
End Using

在断开连接之前,服务器不会从ReadLine 返回 - 即使发送了 CR。如果我更改为vbLFvbCRLF,它将按预期返回。

是文档有误,还是我在这里搞砸了……?

【问题讨论】:

    标签: c# .net vb.net sockets


    【解决方案1】:

    ReadLine 正在等待查看下一个字符是什么。如果是换行,它想吞下它。如果您向作​​者写入任何其他字符,这也会使其返回该行。

    这是对线路终结符的历史混淆的不幸推论。 TextReader 记住它可能需要吞下它读取的下一个字符(并立即返回该行)可能更有意义,但这就是生活。

    【讨论】:

    • 啊 - 非常有道理,但完全没用 - 因为消息以 CR 结尾,没有更多数据要发送。
    • 至少,关于这个怪癖的文档应该更加公开。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2019-03-14
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多