I am trying to write an iOS application which listens for TCP broadcasts and acts on the data. More advanced implementations seem to suggest using background threads and raw sockets to implement this kind of feature, but I thought as a first attempt I would use CFSocket to keep things simple.
The problem is that when I run it, it’s fine , but it run in main thread,don’t run in a new thread.
why doesn’t the callback function run in a background thread?
Here is the code:
- (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);
}
the callback function:
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;
}
}
You may want to use cocoaasyncsocket: it will make your life much easier.
http://code.google.com/p/cocoaasyncsocket/