如何使用NSStreamEventOpenCompleted回调NSStreamDelegate?

时间:2012-09-26 05:19:25

标签: ios iphone cocoa-touch nsstream

我一直在研究NSStreamDelegate,我已经实现了回调,我已经初始化了输入和输出流ilke this ...

    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStringRef host = CFSTR("74.125.224.72");
    UInt32 port = 2270;

    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &inputStream, &writeStream);

    if (writeStream && inputStream) {

        inputStream = (__bridge  NSInputStream *)readStream;
        [inputStream setDelegate:self];
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [inputStream open];

        outputStream = (__bridge  NSOutputStream *)writeStream;
        [outputStream setDelegate:self];
        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream open];
     }

即使在打开后,两个流都没有使用callback(stream:(NSStream *)theStream handleEvent:)调用流NSStreamEventOpenCompleted。任何人都可以帮助我,我在这里做错了什么。或者有什么可能性NSStreamEventOpenCompleted将不被调用,我在文档中看到,如果打开失败,它将不会调用它,如果是这样,为什么打开流失败。有什么想法吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我使用非常相似的代码,它对我来说很好。 请尝试下面的代码。

   NSString* host = @"192.168.2.105";
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    UInt32 port = 8008;

    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)(host), port, &readStream, &writeStream);

    if (writeStream && readStream) {

        self.InputStream = (__bridge  NSInputStream *)readStream;
        [self.InputStream setDelegate:self];
        [self.InputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [self.InputStream open];

        self.OutputStream = (__bridge  NSOutputStream *)writeStream;
        [self.OutputStream setDelegate:self];
        [self.OutputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [self.OutputStream open];
    }

如果它不适合您,我可以发送一个实现TCP客户端和服务器的小应用程序作为示例。