4

我目前正在尝试在后台线程中运行我的整个网络内容,因为当服务器无法访问(即)时,它当前阻塞了主线程。

我目前正在通过以下代码创建网络连接。有没有一种简单的方法可以在新的后台线程中运行它?

我怎样才能将收到的消息扔回主线程?如何通过后台线程发送消息?

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ipAdress, port, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[inputStream open];
[outputStream open];
4

1 回答 1

5

是一个完全符合您所说的教程。虽然它更侧重于音频流,但原理完全相同(即在产生工作线程、让它与父线程对话等方面)。

这个想法很简单..您创建一个新线程并让它处理流工作,然后您使用属于您刚刚创建的线程的运行循环调度流阅读器。流将具有回调,当某些事件发生时将触发(即您获得一些数据,连接超时等)。在回调方法中,您可以警告或与主线程(这是处理 UI 的线程)通信.

这里有一些代码可以为你指明正确的方向,但是如果你从上面的教程下载代码并按照.. 你会得到它:

// create a new thread
internalThread =
                [[NSThread alloc]
                    initWithTarget:self
                    selector:@selector(startInternal)
                    object:nil];
            [internalThread start];

// creating a stream inside the 'startInternal' thread*
stream = CFReadStreamCreateForHTTPRequest(NULL, message);

// open stream
CFReadStreamOpen(stream) 

// set callback functions
// ie say: if there are bites available in the stream, fire a callback etc
CFStreamClientContext context = {0, self, NULL, NULL, NULL};
CFReadStreamSetClient(
        stream,
        kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
        ASReadStreamCallBack,
        &context);

// schedule stream in current thread runloop, so that we DON'T block the mainthread
CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);

// create the callback function to handle reading from stream
// NOTE: see where else in the code this function is named (ie CFReadStreamSetClient)
static void ASReadStreamCallBack
(
   CFReadStreamRef aStream,
   CFStreamEventType eventType,
   void* inClientInfo
)
{
    //handle events you registered above
    // ie
    if (eventType == kCFStreamEventHasBytesAvailable) {
        // handle network data here..
        ..
        // if something goes wrong, create an alert and run it through the main thread:
        UIAlertView *alert = [
            [[UIAlertView alloc]
                initWithTitle:title
                message:message
                delegate:self
                cancelButtonTitle:NSLocalizedString(@"OK", @"")
                otherButtonTitles: nil]
            autorelease];
            [alert
                performSelector:@selector(show)
                onThread:[NSThread mainThread]
                withObject:nil
                waitUntilDone:NO];        
    }          
}
于 2013-03-26T08:39:07.613 回答