iosobjective-cnsinputstreamnsoutputstreamcfreadstream

NSOutputStream's hasSpaceAvailable method always returns False


In my app, I need to use polling instead of run loop while performing certain operations over the network.

My code looks like below

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

and the viewControler.m is as follows

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

The server on receiving some data replies back with a "Hello" Message

On running the above code It always returns that there is noSpaceAvailable/ noBytesAvailable to write or read from the output and input stream respectively.

I'm wondering if I'm missing anything here.


Solution

  • Figured it out. Was a silly mistake. Should have waited until the readstream had bytes available to read.

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