NSStream没有提供任何数据

时间:2013-12-06 23:06:22

标签: ios objective-c sockets stream telnet

我正在尝试在iOS上编写telnet客户端,但我无法正确设置流。我认为它们有效,但每次触发委托方法时我都会得到空缓冲区。

以下是我设置流的方式:

self.manager = [[TelnetManager alloc] init];

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)[[NSURL URLWithString:@"arda.pp.ru"] host], 7000, &readStream, &writeStream);

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

以下是处理事件的管理器上的委托方法:

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    if (eventCode == NSStreamEventHasBytesAvailable) {
        NSLog(@"We got some data over here");
            if(!_data) {
                _data = [NSMutableData data];
            }
            uint8_t buf[1024];
            unsigned int len = 0;
            len = [(NSInputStream *)aStream read:buf maxLength:1024];
        NSLog(@"length - %d", len);
        NSLog(@"buf:%s", buf);
            if(len) {
                [_data appendBytes:(const void *)buf length:len];
                _bytesRead = @([_bytesRead intValue]+len);
            } else {
                NSLog(@"no buffer!");
            }
    }
}

它被触发,但缓冲区始终为空,并且记录了“无缓冲区”。 我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

您的代码实际上没有任何问题。我用它连接到telnet服务器,它工作正常。

在代码中,len为0时会记录“无缓冲区”,这意味着已达到缓冲区的结束。对于telnet服务器,这通常意味着服务器断开连接或服务器退出。