我正在尝试在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!");
}
}
}
它正在被激发,但缓冲区总是空的,并且记录"没有缓冲区"。我的代码出了什么问题?
实际上您的代码没有任何问题。我用它连接到一个telnet服务器,它工作得很好。
在您的代码中,当len
为0时,会记录"无缓冲区",这意味着已经到达缓冲区的末尾。在telnet服务器的情况下,这通常意味着服务器断开了您的连接,或者服务器退出。