objective-cmacosnsnetservice

NSNetService NSNetServiceListenForConnections use and checking for availability?


I'm creating an application that uses NSNetService to publish a server, and I've come across the NSNetServiceListenForConnections option that can be used in OS X 10.9 with the publishWithOptions: method. This new options is highlighted in the "What's New in OS X 10.9" page provided by Apple. It states If you send the NSNetServiceListenForConnections option flag in the options value passed to publishWithOptions:, OS X automatically handles all of the connection management for you, however, I don't see how this a new behavior? I currently just call the publish method and wait for the ServerAcceptCallBack, which is set by the CFSocketCreate method. I doesn't seem to make this any easier?

I'm following some of Apple's code from the CocoaEcho example, which gets a port and opens a CFSocket. I know you can pass 0 as the port parameter for the initWithDomain: name: port: method, but that chooses a "random" port, and I'm guessing that that's not a 100% safe thing to do. I thought that NSNetServiceListenForConnections might have something to do with that, but going by the description, it doesn't.

So to my actual question, after all the rambling:

What does the NSNetServiceListenForConnections option actually do, and (why) should I use it?

Side question: If I should use it, how do I check for availability? I've been told to use if (&NSNetServiceListenForConnections != NULL), but NSNetServiceListenForConnections is an NSUInteger so I can't get the address (via &)


Solution

  • With this option, you don't have to open or manage the sockets at all (i.e. no calling CFSocketCreate). It creates the socket for you. Although I'm finding in 10.9.2 it isn't closing the socket properly if you call stop on the netService, but I'm still investigating. (It did seem to be closing them in 10.9.0 and 10.9.1). The socket seems to stay open until you quit the app.