NSOutputStream 的 hasSpaceAvailable 方法总是返回 False



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

我的代码如下

-(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;
}

和viewcontroller。M如下

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

服务器在接收到一些数据时返回一个"Hello"消息

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

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

明白了。是个愚蠢的错误。应该等到读流有字节可读。

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

相关内容

  • 没有找到相关文章

最新更新