Search code examples
ioscocoabonjournsstream

bytesWritten, but other device never receives NSStreamEventHasBytesAvailable event


I have set up a Bonjour network between an iPhone and a Mac.

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.

The iPhone starts by sending a code (an integer) to the Mac. The Mac successfully receives it.

After a pause for user input and processing, the Mac initiates sending a code to the iPhone:

NSInteger bytesWritten = [self.streamOut write:buffer maxLength:sizeof(uint8_t)];
// bytesWritten is 1.

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.

Any ideas what could be wrong?


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.

So there must be something wrong with the iPhone’s input stream. But I doublechecked:

  • iPhone’s self.streamIn is correctly typed as NSInputStream in the h file
  • iPhone receives 2 NSStreamEventOpenCompleted events, and I check the class of the stream arg. One isKindOfClass:[NSOutputStream class], the other isn’t.
  • iPhone never receives NSStreamEventEndEncountered, NSStreamEventErrorOccurred, or NSStreamEventNone.
  • As noted above, following the Mac’s write to output stream, iPhone’s input stream status is 2, NSStreamStatusOpen.

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:

CFReadStreamRef readStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &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);
}

Update2: Info responsive to alastair’s comment:

Socket Options

The retain, release, and copyDescription callbacks are set to NULL. The optionFlags are set to acceptCallback.

Socket Creation

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):

/**
 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)&acceptSocketCallback, &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 *)&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(&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:&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(&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;
}

Runloop Scheduling

Yes, all 4 streams are scheduled in the runloop, all using code equivalent to what I posted in the first update above.

Runloop Blocking:

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.


Update4, Stream Ports?

Noa's debugging suggestion gave me the idea to examine the stream properties further:

NSNumber *nTest = [self.streamIn propertyForKey:NSStreamSOCKSProxyPortKey]; // always null!

I had assumed that the streams were hanging onto their ports, but surprisingly, nTest 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 works. If a stream doesn't need to hang onto its port assignment once created, what is the purpose of the port property?

Maybe the port property is not accessible directly? But nTest is always null in the following, too:

    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)

Solution

  • The trouble was this line:

    CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);
    

    This would have been OK if I were only receiving data on the iPhone end. But I was creating a pair of streams, not just an input stream, so below this code I was creating a write stream:

    CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, NULL, &writeStream); 
    

    The CFStream Reference says, “If you pass NULL [for readStream], this function will not create a readable stream.” It doesn’t say that if you pass NULL, you’ll render a previously created stream inoperable. But that is apparently what happens.

    One strange artifact of this setup was that if I opened the streamIn first, I would have the opposite problem: The iPhone would get hasByteAvailable events, but never a hasSpaceAvailable event. And as noted in the question, if I queried the streams for their status, both would return NSStreamStatusOpen. So it took a long time to figure out where the real mistake was.

    (This sequential stream creation was an artifact of a test project I had set up months before, in which I tested data moving in only one direction or the other.)

    SOLUTION

    Both streams should be created as a pair, in one line:

    CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, &writeStream);