问题描述
我是不是密集在这里? StreamReader.ReadLine 指出:
Am I being dense here? StreamReader.ReadLine states that:
一个行被定义为一个字符序列后跟一个换行符(\ N),回车(\ r)或回车后紧跟一个换行符(\ r \ N )
那么,为什么不这项工作按预期?
So, why doesn't this work as expected?
' 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发送。如果我更改为 vbLF
或 vbCRLF
它会返回预期。
The server will not return from ReadLine
until a disconnect - even though CR is sent. If I change to a vbLF
, or vbCRLF
it'll return as expected.
是文档错了,还是我拧东西在这里......?
Are the docs wrong, or am I screwing something up here....?
推荐答案
的ReadLine
正在观望下一个字符是什么。如果它是一个换行符,它要吞下它。如果你写的任何其他字符的作家,这将使它返回行了。
ReadLine
is waiting to see what the next character is. If it's a line feed, it wants to swallow it. If you write any other characters to the writer, that'll make it return the line too.
这是历史的混乱行结束的不幸的必然结果。这或许会更有意义的的TextReader
要记住,它需要潜在吞下一个字符读取它(并立即返回行),但生活就是这样。
It's an unfortunate corollary of the historical confusion over line terminators. It would probably have made more sense for TextReader
to remember that it needed to potentially swallow the next character it read (and return the line immediately) but such is life.
这篇关于StreamReader.ReadLine和CR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!