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:
- Two packets, each containing 1,000 bytes, arrive almost immediately.
- Your callback is invoked with
kCFStreamEventHasBytesAvailable
because there are 2,000 bytes waiting. - You're code loops though the
while
loop twice, consuming 1,000 bytes each time. - The
while
loop exits because theCFReadStream
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? - Another packet, containing 1,000 bytes, arrives.
- Your callback is invoked again with
kCFStreamEventHasBytesAvailable
because there are 1,000 more bytes waiting. Are you prepared for this second callback? - Steps 5 & 6 occur twice more.
Jon-Eric
2010-10-15 19:49:37