views:

378

answers:

1

Am I being dense here? StreamReader.ReadLine states that:

A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r") or a carriage return immediately followed by a line feed ("\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

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....?

+5  A: 

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.

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.

Jon Skeet
Ahh - makes perfect sense, and makes it perfectly useless - since the message ends in CR, there's no more data to send.
Mark Brackett