Reputation: 61
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 "kCFStreamEventHasBytesAvailable"
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?
thanks
Upvotes: 0
Views: 1952
Reputation: 17275
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:
kCFStreamEventHasBytesAvailable
because there are 2,000 bytes waiting.while
loop twice, consuming 1,000 bytes each time.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?kCFStreamEventHasBytesAvailable
because there are 1,000 more bytes waiting. Are you prepared for this second callback?Upvotes: 2