5

我在 iPhone 上使用 AsyncSocket 与服务器通信。AsyncSocket 基于运行循环,但我的应用程序基于线程。这意味着,我启动一个新线程来写入数据并等待直到在同一个线程上收到响应。但是我不能直接从另一个线程调用 AsyncSocket 的方法,我必须使用:

[self performSelectorOnMainThread:@selector(writeSomeData:) withObject:dataToWrite waitUntilDone:YES];

它确实有效,但我无法从以这种方式调用的方法“writeSomeData:”获得响应,因为 performSelectorOnMainThread 什么也不返回。

writeSomeData: 方法执行以下操作:

-(NSData *)writeData:(NSData *)dataToWrite {
    dataReceived = nil; // AsyncSocket writes data to this variable
    [asyncSocket writeData:dataToWrite withTimeout:-1 tag:0];
    [asyncSocket readDataToData:[@"<EOF" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    int counter = 0;
    while (dataReceived == nil && counter < 5) {
        // runLoop is [NSRunLoop currentRunloop]
        [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.3]];
        ++counter;
    }

    return [dataReceived copy];
}

我可以通过访问类变量“dataReceived”来获得响应,但此时它的内容发生了变化。

谁能告诉我如何在单独的线程上使用 AsyncSocket (或者通常,如何处理基于运行循环的类),以便如果我调用该类的方法,它会阻塞,直到该方法被执行并收到响应?

谢谢你。

4

1 回答 1

-1

尝试使用GCD(Grand Central Dispatch) 在单独的线程上写入数据,然后在写入数据的那一刻返回主线程。你可以这样做:

// call this on the main thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    NSData *data = [self writeData:dataToWrite];
    dispatch_async(dispatch_get_main_queue(), ^{
        // do something with the data on the main thread.
    });
});

我希望这样的事情可以帮助你......

于 2012-02-03T16:15:56.383 回答