3

我正在编写一个消息应用程序,它使用 NSStream 与用 Python 编写的服务器进行通信。服务器与配套的 Python 客户端完美配合。但是当我用 NSStream 连接到它时, NSInputStream 似乎没有得到任何数据。然而,NSOutputStream 可以完美运行。我像这样打开字符串:

-(void)openStream
{
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"tihmstar.dyndns.org", 80,       &readStream, &writeStream);

    inputStream = (__bridge_transfer NSInputStream *)readStream;
    outputStream = (__bridge_transfer NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];

    [self auth];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"InitCompleted" object:nil];
}

委托方法是这样的:

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
    {
        NSLog(@"Handle Event - ");
        switch (streamEvent)
        {
            case NSStreamEventOpenCompleted:
                NSLog(@"Stream opened");
                break;

            case NSStreamEventHasBytesAvailable:
                NSLog(@"Bytes Available!");
                if(theStream == inputStream)
                {
                    NSLog(@"inputStream is ready.");

                    uint8_t buf[1024];
                    unsigned int len = 0;

                    len = [inputStream read:buf maxLength:1024];

                    if(len > 0)
                    {
                        NSMutableData* data=[[NSMutableData alloc] initWithLength:0];

                        [data appendBytes: (const void *)buf length:len];

                        NSString* string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
                        NSLog(@"Server said- %@", string);
                        [self messageReceived:[string lowercaseString]];
                    }
                }
                break;

            case NSStreamEventErrorOccurred:
                NSLog(@"Can not connect to the host!");
                break;

            case NSStreamEventEndEncountered:
                NSLog(@"End Encountered");
                break;

            case NSStreamEventHasSpaceAvailable:
                NSLog(@"Space Availible.");
                break;

            default:
                NSLog(@"Unknown event- %u", streamEvent);
        }
    }

我的问题是这种情况 NSStreamEventHasBytesAvailable 永远不会被调用,因此永远不会收到来自服务器的消息。有人对此有任何解决方案吗?我在 StackOverflow 上找到了一些相关的问题,但没有一个得到回答。

提前致谢。

4

2 回答 2

1

我只是在研究代码。尝试删除 NSInputStream 的委托。我正在研究另一个Using NSXMLParser initWithStream: no parser delegate methods received

它处理类似的情况。

于 2013-12-29T06:26:06.590 回答
0

我不知道你的问题的确切答案,但我确切地知道你不应该打电话

[self auth];

NSStream 立即打开后。你必须等待

NSStreamEventHasSpaceAvailable

为您的 NSOutputStream 事件,然后仅在其中写入数据。

于 2014-06-17T05:06:04.603 回答