在运行循环上安排读取流 - iOS

时间:2011-03-02 05:44:55

标签: iphone objective-c cocoa-touch sockets

我是Cocoa / iOS的新手 - iphone平台

我正在尝试使用Core Foundations处理网络流。我正在关注CFNetworking指南,但我无法进行简单的测试。以下编译并运行但没有记录到NSLog。

我向CFReadStreamSetClient提供Callback,clientCB,并在运行循环上调度readStream(至少这是个想法)。

我期待CallBack报告一些事情。

有人能告诉我哪里出错了吗?我已经telnet到这个服务器,它的工作原理。任何建议都会有所帮助。

感谢。

void clientCB(CFReadStreamRef stream, CFStreamEventType event, void *myPtr)
{
    switch(event) {
        case kCFStreamEventHasBytesAvailable:{
            UInt8 buf[BUFSIZE];
            CFIndex bytesRead = CFReadStreamRead(stream, buf, BUFSIZE);
            if (bytesRead > 0) {
              NSLog(@"Server has data to read!");
            }
            break;
        }
        case kCFStreamEventErrorOccurred:
            NSLog(@"A Read Stream Error Has Occurred!");
        case kCFStreamEventEndEncountered:
            NSLog(@"A Read Stream Event End!");
        default:
            break;
    }

}



- (IBAction) connectToServer: (id) sender

{
    CFReadStreamRef readStream; 
    CFWriteStreamRef writeStream;
    CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)@"irc.freenode.net");
    CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host, 6667, &readStream, &writeStream);

    CFStreamClientContext myContext = {
        0,
        self,
        (void *(*)(void *info))CFRetain,
        (void (*)(void *info))CFRelease,
        (CFStringRef (*)(void *info))CFCopyDescription
    };

    CFOptionFlags registeredEvents = kCFStreamEventHasBytesAvailable |
                                kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;

    if(CFReadStreamSetClient(readStream, registeredEvents, clientCB, &myContext))
    {
        CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    }

}

1 个答案:

答案 0 :(得分:1)

您似乎忘了打电话给CFReadStreamOpen。​​

    if(CFReadStreamSetClient(readStream, registeredEvents, clientCB, &myContext))
    {
        CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    }

    if (!CFReadStreamOpen(readStream)) {
        /* error handling */
    }
}