2011-10-11 63 views
1

我想寫一個iOS應用程序,它監聽TCP廣播並對數據進行操作。更高級的實現似乎建議使用後臺線程和原始套接字來實現這種功能,但我認爲這是第一次嘗試使用CFSocket來保持簡單。iphone網絡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

我認爲行* CFRunLoopRef cfrl = CFRunLoopGetCurrent(); *與這個有關... – Krishnabhadra

+0

你的想法是什麼? – Gaojian922188

回答