在iOS6.1上,以下代码应该完全相同,但是当我忘记编写addr.sin_len = sizeof(adde)
时,第一个块失败了。原始错误是:
GOT EVENT FROM INPUT Event: 8
ERR: Error Domain=NSPOSIXErrorDomain Code=12 "The operation couldn’t be completed. Cannot allocate memory"
在添加缺失行以设置结构大小后,第一个块就像第二个一样工作。可能其他开发人员会在这篇文章中看到错误消息和旅行。
代码:
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
#if 1 // LONG WAY
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr); // ORIGINALLY WAS MISSING
addr.sin_family = AF_INET;
addr.sin_port = htons(5566);
int ret = inet_pton(AF_INET, "192.168.1.2", &(addr.sin_addr.s_addr)); // IPv4
assert(ret == 1);
NSLog(@"CONNECT");
CFDataRef address = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)&addr, sizeof(addr));
assert(address);
CFHostRef macMini = CFHostCreateWithAddress(kCFAllocatorDefault, address);
CFRelease(address);
assert(macMini);
// (tried, makes not difference) CFHostScheduleWithRunLoop (macMini, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, macMini, 5566, &readStream, &writeStream);
CFRelease(macMini);
#else // SHORT WAY
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, CFSTR("192.168.1.2"), 5566, &readStream, &writeStream);
#endif
assert(readStream);
assert(writeStream);
iStream = CFBridgingRelease(readStream);
oStream = CFBridgingRelease(writeStream);
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];
NSLog(@"ISTREAM %@ status=%d", iStream, [iStream streamStatus]);
NSLog(@"ERR: %@", [iStream streamError]);
[oStream setDelegate:self];
[oStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[oStream open];
NSLog(@"OSTREAM %@ status=%d", oStream, [oStream streamStatus]);
NSLog(@"ERR: %@", [oStream streamError]);
答案 0 :(得分:1)
问题是没有设置sin_len
。关于上面两组代码的好处是你可以看到如何以任何一种方式完成任务。