现在的位置: 首页 > 综合 > 正文

线程server如何做?已完成

2018年02月14日 ⁄ 综合 ⁄ 共 946字 ⁄ 字号 评论关闭

aysncsocket在发起连接时必须在主线程中进行,,否则异步的委托返回将会出现无反应等现象。所以如果开启连接前若是在子线程中进行,则连接必须返回主线程performSelectorOnMainThread。


现在纠结如何将这个server移到线程中!?

问题早就解决了。答案就是RunLoop~

下面贴代码!仅供参考!具体问题具体分析!

- (void)initHttpServer
{
    CFRunLoopSourceContext context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
    CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
    
    HTTPServer *httpServer = [HTTPServer getInstance];
	[httpServer setType:@"_http._tcp."];
	[httpServer setConnectionClass:[MyHTTPConnection class]];
	NSError *error;
    if(![httpServer start:&error])
	{
		NSLog(@"Error starting HTTP Server: %@", error);
	}
    
    BOOL runAlways = YES; // Introduced to cheat Static Analyzer
    while (runAlways) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        CFRunLoopRun();
        [pool drain];
    }

    // Should never be called, but anyway
    CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
    CFRelease(source);
}然后用detachnewthread调一下这个函数就OK了!

抱歉!评论已关闭.