A: 

When you get kCFStreamEventHasBytesAvailable, it's possible that only some of the bytes are available and the remaining bytes won't arrive until later.

Imagine you are expecting a total of 5,000 bytes.

Because of unpredictable network timings, this is one scenario:

  1. Two packets, each containing 1,000 bytes, arrive almost immediately.
  2. Your callback is invoked with kCFStreamEventHasBytesAvailable because there are 2,000 bytes waiting.
  3. You're code loops though the while loop twice, consuming 1,000 bytes each time.
  4. The while loop exits because the CFReadStream has no more bytes available. Does your code recognize that you don't yet have all your data even though there aren't currently any more bytes waiting?
  5. Another packet, containing 1,000 bytes, arrives.
  6. Your callback is invoked again with kCFStreamEventHasBytesAvailable because there are 1,000 more bytes waiting. Are you prepared for this second callback?
  7. Steps 5 & 6 occur twice more.
Jon-Eric