开发者

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? thanks


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜