Bonjour, encore

Let’s see if I can dodge the NDA on this one…

So I’m working on peer-to-peer networking for the new 3.0 chapters in our iPhone book. One thing I believe they’ve pointed out publicly is that the framework works either with Bluetooth (which is the new hotness), or with a connection you provide.

For a number of reasons, I’ve been working on making good with the latter. I figured it would be pretty reasonable to do it with Bonjour. Of course, there’s a reason we only showed client-side Bonjour in the current Network I/O chapter, and then only with HTTP browsing. Bonjour is just about service discovery; to use a service, you talk raw sockets. So while it’s easy enough to get participants to discover each other over wifi, for one or both to be a server, you have to set up and bind a socket, probably using the C-based BSD sockets APIs. Tried and true, but probably pretty scary for our readership.

I started working with the usual stream metaphors, but happened across NSFileHandle, a Cocoa object to wrap Unix file descriptors. If you can set one up with a plain ol’ socket, it does a lot of the asychronous connection management for you. To wit: instead of managing your own little buffer and looping over calls to NSOutputStream‘s write:maxLength:, you can just call a big ol’ writeData:. Plus, you get asynchronous events like connections and new data as NSNotifications. Examples in the Bonjour SDK’s Picture Sharing and Picture Sharing Browser sample code, as well as an O’Reilly article from 2006, How to Write a Cocoa Web Server.

Finally got it working just after lunch. The simulator and a 2nd gen Touch (“Moogle”) discover each other and send each other test messages over a generic “receive some data” method call:

(click for full-size image)

No sample code today; after a hundred false starts, it’s too ragged. I’m going to zip up this working code (it’s in an non-svn’ed “throwaway” directory for experiments), and then plan out something that’s suitable for exposure to daylight.

Previous Post

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.