NSOutputStream的hasSpaceAvailable方法总是返回False

时间:2015-07-08 18:03:07

标签: ios objective-c nsinputstream nsoutputstream cfreadstream

在我的应用中,我需要在通过网络执行某些操作时使用轮询而不是运行循环。

我的代码如下所示

-(id) init
{
    self = [super init];
    if (self) {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    NSURL *host = [NSURL URLWithString:@"http://localhost/"];
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)([host host]), 5525, &readStream, &writeStream);
    _writeStream = [[NSOutputStream alloc] initToMemory];
    _readStream = (__bridge NSInputStream *)(readStream);
    _writeStream = (__bridge NSOutputStream *)(writeStream);
    [_readStream open];
    [_writeStream open];
  }
   return self;
}

-(void) writeIntoNetworkWith:(NSString *)info
{
if ([self.writeStream hasSpaceAvailable]) {
    NSData * data = [[NSData alloc] initWithData:[info dataUsingEncoding:NSUTF8StringEncoding]];
    [self.writeStream write:[data bytes] maxLength:[data length]];
}
else
    NSLog(@"Write Stream Not Available");
}
-(NSString *) readFromNetwork
{
   NSMutableString * send;
   if ([self.readStream hasBytesAvailable])
  {
    uint8_t buffer[1024];
    int len;
    len = [self.readStream read:buffer maxLength:1024];
    if (len >0)
    {
        send = [[NSMutableString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];
    }
}
return send;
}

和viewControler.m如下

- (void)viewDidLoad {
  [super viewDidLoad];
  SuperTestClass * n = [[SuperTestClass alloc]init];
  NetworkReadAndWrite * obj = [[NetworkReadAndWrite alloc]init];
  [obj writeIntoNetworkWith:@"Hello World"];
  [obj readFromNetwork];
}

接收一些数据的服务器回复" Hello"消息

运行上面的代码它总是返回noSpaceAvailable / noBytesAvailable分别从输出和输入流写入或读取。

我想知道我是否在这里遗漏了什么。

1 个答案:

答案 0 :(得分:1)

想出来。是一个愚蠢的错误。应该等到读取流有可读取的字节。

while(1)
{

    if ([self.readStream hasBytesAvailable])
    {
        uint8_t buffer[1024];
        int len;
        len = [self.readStream read:buffer maxLength:1024];
        if (len >0)