在iPhone上使用带有辅助线程的AsyncSocket
我在iPhone上使用AsyncSocket与服务器通信。AsyncSocket基于运行循环,但我的应用程序基于线程。这意味着,我启动一个新线程来写入数据,并等待同一线程上收到响应。但是我不能直接从另一个线程调用AsyncSocket的方法,我必须使用:在iPhone上使用带有辅助线程的AsyncSocket,iphone,cocoa-touch,nsthread,asyncsocket,nsrunloop,Iphone,Cocoa Touch,Nsthread,Asyncsocket,Nsrunloop,我在iPhone上使用AsyncSocket与服务器通信。AsyncSocket基于运行循环,但我的应用程序基于线程。这意味着,我启动一个新线程来写入数据,并等待同一线程上收到响应。但是我不能直接从另一个线程调用AsyncSocket的方法,我必须使用: [self performSelectorOnMainThread:@selector(writeSomeData:) withObject:dataToWrite waitUntilDone:YES]; 它确实可以工作,但我无法从以这种方式
[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];
}
// 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.
});
});
-(NSData*)写入数据:(NSData*)数据写入{
dataReceived=nil;//AsyncSocket将数据写入此变量
[asyncSocket writeData:dataToWrite withTimeout:-1标记:0];
[asyncSocket readDataToData:[@”尝试使用GCD
(Grand Central Dispatch)在单独的线程上写入数据,然后在写入数据时返回主线程。您可以这样做:
-(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];
}
// 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.
});
});
我希望这样的东西可以帮助您……为什么您首先想要那个场景?如果您要做的第一件事是阻止它,直到更多或更少的任意未来日期?为什么不使用runloop从线程开始整个过程,并调度结果数据,以便在NSOperationQueue
或全局并发调度队列之一上进行处理?