2013-02-09 64 views
1

在iOS6.1上,以下代碼應該做同樣的事情,但是當我忘記編寫addr.sin_len = sizeof(adde)時,第一個塊失敗。原來的錯誤是:爲什麼當CFStreamCreatePairWithSocketToHost成功時CFStreamCreatePairWithSocketToCFHost失敗

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

回答

1

問題是sin_len沒有設置。上述兩套代碼的好處是你可以看到如何完成任務。

相關問題