程序启动,自以为的,在loop中循环,在loop中加入socket监听端口,还需要loop一直循环么?
答案自然不知道,但事实问题,在这种队列中监听.
导致其他线程出问题了.
1.创建随机队列方法不了解.
2.监听端口的机制学习.
下面是一个错误的示范,时刻留意这个bug.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CFSocketContext ctx = { 0, self, NULL, NULL, NULL };
recvSocket_ = CFSocketCreate(kCFAllocatorDefault,
PF_INET,
SOCK_DGRAM,
IPPROTO_UDP,
kCFSocketDataCallBack,
(CFSocketCallBack)DiscoverReceiveCallback,
&ctx);
if (recvSocket_ == NULL) {
LOG(@"[DSCV] Cannot create listening socket. %d", errno);
return ;
}
int flag = 1;
setsockopt(CFSocketGetNative(recvSocket_), SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
NSData *addrData = [NSData dataWithBytes:&addr length:sizeof(addr)];
if (CFSocketSetAddress(recvSocket_, (CFDataRef)addrData)) {
CFSocketInvalidate(recvSocket_);
CFRelease(recvSocket_);
recvSocket_ = NULL;
LOG(@"[DSCV] Cannot set address to socket.");
return ;
}
LOG(@"recvSocket_------>%@",recvSocket_);
CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, recvSocket_, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
CFRelease(source);
CFRunLoopRun(); });