Problems in getting data from CFStreamCreatePairWithSocketToHost
I'm building an iPhoe app with a socket to a PC app , I need to get an image from this PC app. It's my first time using "CFStreamCreatePairWithSocketToHost".After I establish the socket with "NSOperation" I call
CFStreamClientContext streamContext = {0, self, NULL, NULL, NULL};
BOOL success = CFReadStreamSetClient(myReadStream, kMyNetworkEvents,MyStreamCallBack,&streamContext);
CFReadStreamScheduleWithRunLoop(myReadStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
then I call
CFWriteStreamWrite(myWriteStream, &writeBuffer, 3);
// Open read stream.
if (!CFReadStreamOpen(myReadStream)) {
// Notify error
}
.
.
.
while(!cancelled && !finished) {
SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.25, NO);
if (result == kCFRunLoopRunStopped || result == kCFRunLoopRunFinished) {
break;
}
if (([NSDate timeIntervalSinceReferenceDate] - _lastRead) > MyConnectionTimeout) {
// Call timed out
cancelled = YES;
break;
}
// Also handle stream status
CFStreamStatus status = CFReadStreamGetStatus(myReadStream);
}
and then when I get "kCFStreamEventHasBytesA开发者_如何学编程vailable"
I use
while (CFReadStreamHasBytesAvailable(myReadStream))
{
CFReadStreamRead(myReadStream, readBuffer, 1000);
//and buffer the the bytes
}
It's unpredictable , sometimes I get the whole picture , sometime I got just part of it , and I can't understand what make the different.
can someone has an idea what is wrong here?
thanksWhen 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.
精彩评论