在两个不同的线程中运行两个NSStream

时间:2012-10-13 04:20:47

标签: objective-c ios nsthread nsstream cfstream

我的应用程序在一个单独的线程中运行网络任务 - 它从我的服务器获取数据,处理它并持续显示结果。当我在一个线程中只有一个这样的网络连接时,这很好用。但是,如果我运行具有类似网络任务的第二个线程,第二个线程工作正常,但第一个停止响应。我的类调度网络进程的代码如下。关于这里可能出现什么问题的任何想法?

NSThread * nThread;

- (NSThread *)networkThread {
    nThread = nil;

        nThread =
        [[NSThread alloc] initWithTarget:self
                                selector:@selector(networkThreadMain:)
                                  object:nil];
        [nThread start];

    DLog(@"thread: %@, debug description: %@", nThread, nThread.debugDescription);
    return nThread;
}


- (void)networkThreadMain:(id)unused {
    do {
            [[NSRunLoop currentRunLoop] run];
    } while (YES);
}

- (void)scheduleInCurrentThread:(id)unused
{
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSRunLoopCommonModes];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSRunLoopCommonModes];
}

-(BOOL) connectWithError:(NSString **) e
{
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", [server port], &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *) readStream;
    outputStream = (__bridge NSOutputStream *) writeStream;

    [inputStream setDelegate:self];
    [outputStream setDelegate:self];

    [self performSelector:@selector(scheduleInCurrentThread:)
                 onThread:[self networkThread]
               withObject:nil
            waitUntilDone:YES];

    [inputStream open];
    [outputStream open];
}

0 个答案:

没有答案