1

After asking this question Writing to TcpClient and NetworkStream it appears i must write yet another stream which will read in a smaller stream and keep going until i get the size i like (or until error/timeout).

Is there anything built in? Or in a popular 3rd party library? I just want to make sure my TCP readlength is big enough to initialize my structs or fill an array before i start doing operations on it. So i'd like Read() to block until it is ready. Perhaps throw an exception when the underlying stream (TCP) timeout or is closed on the other size. (or is EOF which would be useful with file IO streams).

Community
  • 1
  • 1

1 Answers1

1

I think BinaryReader.ReadBytes() is exactly what you want. It can return less than the requested number of bytes, but, according to the documentation, that only happens when the end of the stream is reached.

svick
  • 236,525
  • 50
  • 385
  • 514
  • I tried it and +1. Now after some testing i see that it does not block. Running many clients at once has a few crash with an exception due to length being incorrect or not enough data/corruption –  Jul 15 '12 at 03:28
  • nope. I use BeginAcceptTcpClient (its async). Each thread BeginAcceptTcpClient create gets a tcpclient for that connection and thats the only thread that has access to that client. The server/listener is just in a never ending loop. –  Jul 15 '12 at 19:55
  • Fortunately BinaryReader isnt sealed so i inherit it and only overrided the read function. Now it will block until all my data is filled. –  Jul 15 '12 at 19:57