1

在 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]);
4

1 回答 1

1

问题是sin_len没有设置。拥有上述两组代码的好处是,您可以看到如何以任何一种方式完成任务。

于 2013-02-10T13:17:04.153 回答