title: Async CFStream networking with runloop
body: <p>I am trying to implement async tcp networking with runloop.
  currently I manage to connect, but when I try to send something I get that -1 bytes have been written - but CFWriteStreamCopyError returns null.</p>
  
  <p>code sample below, first function connects, second send a simple message.
  any help will be appreciated, including random bug spotting (I am new to objective-c and to iphone development in general).</p>
  
  <pre><code>struct header
  {
      uint32_t length;
      uint32_t type;
  } header;
  
  - (void) connect
  {
      NSLog(@"Attempting to (re)connect to %@:%d", m_host, m_port);
      while(TRUE)
      {
          CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)m_host);
          if (!host)
          {
              NSLog(@"Error resolving host %@", m_host);
              [NSThread sleepForTimeInterval:5.0];
              continue;
          }
          CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host , m_port, &amp;m_in, &amp;m_out);
          CFRelease(host);
  
          if (!m_in)
          {
              NSLog(@"Error");
          }
  
          CFStreamClientContext context = {0, self,nil,nil,nil};
  
          if (CFReadStreamSetClient(m_in, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkReadEvent, &amp;context))
          {
              CFReadStreamScheduleWithRunLoop(m_in, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
          }
  
          if (CFWriteStreamSetClient(m_out, kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkWriteEvent, &amp;context))
          {
              CFWriteStreamScheduleWithRunLoop(m_out, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
          }
  
  
          BOOL success = CFReadStreamOpen(m_in);
          CFErrorRef error = CFReadStreamCopyError(m_in);
          if (!success || (error &amp;&amp; CFErrorGetCode(error) != 0))
          {
              NSLog(@"Connect error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
              [NSThread sleepForTimeInterval:5.0];
          }
          else 
          {
              NSLog(@"Connected");
              break;
          }
      }
  
  
      [self startSession];
  }
  
  - (void) startSession
  {
      struct header hh;
      hh.type = RTR_CREATE_SESSION;
      hh.length = 0;
      CFIndex res = CFWriteStreamWrite(self.m_out, (const UInt8*)&amp;hh, sizeof(hh));
      NSLog(@"Written %d", res);
  
      CFErrorRef error = CFWriteStreamCopyError(self.m_out);
      if (error)
      {
          NSLog(@"Read error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
          CFRelease(error);
      }
  }
  </code></pre>