title: bytesWritten, but other device never receives NSStreamEventHasBytesAvailable event
body: <p>I have set up a Bonjour network between an iPhone and a Mac.</p>
  
  <p>The user chooses the iPhone’s net service in a table presented in the Mac, and a pair of streams are created and opened on both sides.</p>
  
  <p>The iPhone starts by sending a code (an integer) to the Mac. The Mac successfully receives it.</p>
  
  <p>After a pause for user input and processing, the Mac initiates sending a code to the iPhone:</p>
  
  <pre><code>NSInteger bytesWritten = [self.streamOut write:buffer maxLength:sizeof(uint8_t)];
  // bytesWritten is 1.
  </code></pre>
  
  <p>But the iPhone never gets an NSStreamEventHasBytesAvailable event. I double-checked just before this point, and streamStatus on the iPhone’s NSInputStream is 2, which is NSStreamStatusOpen, as it should be.</p>
  
  <p>Any ideas what could be wrong?</p>
  
  <hr>
  
  <p>Update: I ran a test in which the Mac was the first to send an integer to the iPhone. Again, I got a bytesWritten of 1 from the Mac’s output stream, but the iPhone never got a NSStreamEventHasBytesAvailable event.</p>
  
  <p>So there must be something wrong with the iPhone’s input stream. But I doublechecked:</p>
  
  <ul>
  <li>iPhone’s self.streamIn is correctly typed as NSInputStream in the h file</li>
  <li>iPhone receives 2 NSStreamEventOpenCompleted events, and I check the class of the stream arg. One isKindOfClass:[NSOutputStream class], the other isn’t.</li>
  <li>iPhone never receives NSStreamEventEndEncountered, NSStreamEventErrorOccurred, or NSStreamEventNone.</li>
  <li>As noted above, following the Mac’s write to output stream, iPhone’s input stream status is 2, NSStreamStatusOpen.</li>
  </ul>
  
  <p>Here is the code used to create the iPhone's input stream. It uses CF types because it's done in the C-style socket callback function:</p>
  
  <pre><code>CFReadStreamRef readStream = NULL;
  CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &amp;readStream, NULL);
  if (readStream) {
      CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
      server.streamIn = (NSInputStream *)readStream;
      server.streamIn.delegate = server;
      [server.streamIn scheduleInRunLoop:[NSRunLoop currentRunLoop] 
                                 forMode:NSDefaultRunLoopMode];
      if ([server.streamIn streamStatus] == NSStreamStatusNotOpen)
          [server.streamIn open];
      CFRelease(readStream);
  }
  </code></pre>
  
  <hr>
  
  <p>Update2: Info responsive to alastair’s comment:</p>
  
  <p><strong>Socket Options</strong></p>
  
  <p>The retain, release, and copyDescription callbacks are set to NULL. The optionFlags are set to acceptCallback.</p>
  
  <p><strong>Socket Creation</strong></p>
  
  <p>Here’s the method used to set up the socket on both the iPhone and the Mac, complete with my commented attempts to figure out what is actually going on in this code, which was adapted from various tutorials and experiments (which worked):</p>
  
  <pre><code>/**
   Socket creation, port assignment, socket scheduled in run loop.
   The socket represents the port on this app's end of the connection.
   */
  - (BOOL) makeSocket {
      // Make a socket context, with which to configure the socket.
      // It's a struct, but doesn't require "struct" prefix -- because typedef'd?
  CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL}; // 2nd arg is pointer for callback function   
      // Make socket.
      // Sock stream goes with TCP protocol, the safe method used for most data transmissions.
      // kCFSocketAcceptCallBack accepts connections automatically and presents them to the callback function supplied in this class ("acceptSocketCallback").
      // CFSocketCallBack, the callback function itself.
      // And note that the socket context is passed in at the end.
      self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&amp;acceptSocketCallback, &amp;socketCtxt);
  
      // Do socket-creation error checking.
      if (self.socket == NULL) {
          // alert omitted
          return NO;
      }
  
      // Prepare an int to pass to setsockopt function, telling it whether to use the option specified in arg 3.
      int iSocketOption = 1; // 1 means, yes, use the option
  
      // Set socket options.
      // arg 1 is an int. C-style method returns native socket.
      // arg 2, int for "level." SOL_SOCKET is standard.
      // arg 3, int for "option name," which is "uninterpreted." SO_REUSEADDR enables local address reuse. This allows a new connection even when a port is in wait state.
      // arg 4, void (wildcard type) pointer to iSocketOption, which has been set to 1, meaning, yes, use the SO_REUSEADDR option specified in arg 3.
      // args 5, the size of iSocketOption, which can now be recycled as a buffer to report "the size of the value returned," whatever that is. 
      setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, (void *)&amp;iSocketOption, sizeof(iSocketOption));
  
      // Set up a struct to take the port assignment.
      // The identifier "addr4" is an allusion to IP version 4, the older protocol with fewer addresses, which is fine for a LAN.
      struct sockaddr_in addr4;
      memset(&amp;addr4, 0, sizeof(addr4));
      addr4.sin_len = sizeof(addr4);
      addr4.sin_family = AF_INET;
      addr4.sin_port = 0; // this is where the socket will assign the port number
      addr4.sin_addr.s_addr = htonl(INADDR_ANY);
      // Convert to NSData so struct can be sent to CFSocketSetAddress.
      NSData *address4 = [NSData dataWithBytes:&amp;addr4 length:sizeof(addr4)];
  
      // Set the port number.
      // Struct still needs more processing. CFDataRef is a pointer to CFData, which is toll-free-bridged to NSData.
      if (CFSocketSetAddress(socket, (CFDataRef)address4) != kCFSocketSuccess) {
          // If unsuccessful, advise user of error (omitted)…
          // ... and discard the useless socket.
          if (self.socket) 
              CFRelease(socket);
          self.socket = NULL;
          return NO;
      }
  
      // The socket now has the port address. Extract it.
      NSData *addr = [(NSData *)CFSocketCopyAddress(socket) autorelease];
      // Assign the extracted port address to the original struct.
      memcpy(&amp;addr4, [addr bytes], [addr length]);
      // Use "network to host short" to convert port number to host computer's endian order, in case network's is reversed.
      self.port = ntohs(addr4.sin_port);
      printf("\nUpon makeSocket, the port is %d.", self.port);// !!!:testing - always prints a 5-digit number
  
      // Get reference to main run loop.
      CFRunLoopRef cfrl = CFRunLoopGetCurrent();
      // Schedule socket with run loop, by roundabout means.
      CFRunLoopSourceRef source4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
      CFRunLoopAddSource(cfrl, source4, kCFRunLoopCommonModes);
      CFRelease(source4);
  
      // Socket made
      return YES;
  }
  </code></pre>
  
  <p><strong>Runloop Scheduling</strong></p>
  
  <p>Yes, all 4 streams are scheduled in the runloop, all using code equivalent to what I posted in the first update above.</p>
  
  <p><strong>Runloop Blocking:</strong> </p>
  
  <p>I’m not doing anything fancy with synchronization, multiple threads, NSLocks, or the like. And if I set a button action to print something to the console, it works throughout — the runloop seems to be running normally.</p>
  
  <hr>
  
  <p>Update4, Stream Ports?</p>
  
  <p>Noa's debugging suggestion gave me the idea to examine the stream properties further:</p>
  
  <pre><code>NSNumber *nTest = [self.streamIn propertyForKey:NSStreamSOCKSProxyPortKey]; // always null!
  </code></pre>
  
  <p>I had assumed that the streams were hanging onto their ports, but surprisingly, <code>nTest</code> is always null. It's null in my apps, which would seem to point to a problem -- but it's also null in a tutorial app that <em>works</em>. If a stream doesn't need to hang onto its port assignment once created, what is the purpose of the port property?</p>
  
  <p>Maybe the port property is not accessible directly? But <code>nTest</code> is always null in the following, too:</p>
  
  <pre><code>    NSDictionary *dTest = [theInStream propertyForKey:NSStreamSOCKSProxyConfigurationKey];
      NSNumber *nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
      NSLog(@"\tInstream port is %@.", nTest); // (null)
      nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
      NSLog(@"\tOutstream port is %@.", nTest); // (null)
  </code></pre>