iphone网络cfsocket回调多线程

时间:2011-10-11 05:11:14

标签: iphone

我正在尝试编写一个监听TCP广播并对数据进行操作的iOS应用程序。更高级的实现似乎建议使用后台线程和原始套接字来实现这种功能,但我认为作为第一次尝试,我将使用CFSocket来保持简单。

问题在于,当我运行它时,它很好,但它在主线程中运行,不在新线程中运行。 为什么回调函数不在后台线程中运行?

以下是代码:

- (void)connecToServer{
    int yes = 1;
    CFSocketContext CTX = {0,self,NULL,NULL,NULL};
    _socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketDataCallBack, TCPServerConnectCallBack, &CTX);    
    setsockopt(CFSocketGetNative(_socket), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes));
    struct sockaddr_in addr4;    
    memset(&addr4, 0, sizeof(addr4));    
    addr4.sin_len = sizeof(addr4);    
    addr4.sin_family = AF_INET;    
    addr4.sin_port = htons(6242);    
    addr4.sin_addr.s_addr = inet_addr("");    
    address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&addr4, sizeof(addr4));        
    CFRunLoopRef cfrl = CFRunLoopGetCurrent();    
    CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _socket, 0);    
    CFRunLoopAddSource(cfrl, source, kCFRunLoopCommonModes);    
    CFRelease(source);
}

回调函数:

static void TCPServerConnectCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info){
    NSData *nsdata = (NSData*)data;
    NSUInteger len = [nsdata length];
    Byte *byteData = (Byte*)malloc(len);
    memcpy(byteData, [nsdata bytes], len);
    Byte *userData;
    NetWorkConnect *netWorkConnect = (NetWorkConnect*)info;
    switch(byteData[5]){
        case 2:
            userData = (Byte*)malloc(len-9);
            memcpy(userData, byteData+7, len-9);
            memset(&(netWorkConnect->oQuota), 0, sizeof(netWorkConnect->oQuota));
            [netWorkConnect performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
           break;
        default:
           break;
    }
}

1 个答案:

答案 0 :(得分:0)

你可能想要使用cocoaasyncsocket:它会让你的生活更轻松。 http://code.google.com/p/cocoaasyncsocket/