Luc*_*ùlè 4 networking objective-c
我目前正在尝试在后台线程中运行整个网络,因为当服务器无法访问时,它会阻塞主线程。
我目前正在通过以下代码创建网络连接。有没有简单的方法可以在新的后台线程中运行它?
我该如何将收到的消息退回主线程?一个如何通过后台线程发送消息?
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];
Run Code Online (Sandbox Code Playgroud)
这里是一个教程,完全可以满足您的要求。尽管它更多地侧重于音频流,但是原理是完全相同的(即,在生成工作线程,让它与父线程对话等方面)。
这个想法很简单..创建一个新线程并让它处理流工作,然后使用属于您刚创建的线程的运行循环来调度流读取器。该流将具有在发生某些事件(即,您获得一些数据,连接超时等)时将触发的回调。 。
这是一些代码,可以为您指明正确的方向,但是,如果您从上述教程中下载了代码,然后继续进行操作..,您将获得:
// 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];
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6443 次 |
最近记录: |