I want to implement IPC in a Cocoa application using UNIX domain sockets, with which I have no experience. I found Apple’s CFLocalServer example project, but it’s written in C and looks, well, fairly complicated (and yes, I have read most of it).
Are the techniques demonstrated in CFLocalServer still state-of-the-art, or is there a way to implement UNIX domain sockets in Objective-C with Cocoa/Foundation?
I’m playing with NSSocketPorts and NSFileHandles (which provide a healthy amount of abstraction, which is great for this project) and found some very-related code in Mike Bean’s Networking in Cocoa, but haven’t been able to Make It All Work yet.
Anyone done this before?
In the end, I did use UNIX domain sockets, and they work pretty well. I have launchd set up the socket for my server (but did write code, successfully, to create it myself), and have the client connect to it.
Things I learned:
You can wrap both ends of the connection in NSFileHandle
You do need to use
connect()on the client side to create a connection to the socketYou should make both the client and the server ignore SIGPIPE
If you get called back with zero-length data, it means that the thing on the other end of the socket has disconnected (i.e. the server/client exited). Make sure to close and release your end of the socket in this case — don’t try to read data from it again, or just get another zero-length read callback (for ever and ever)
You’re responsible for delimiting and assembling the messages you send across the socket (a single message sent on one end may be spit into more than one on the other end, or multiple messages might be merged)
I would be happy to share or publish code, just haven’t had the time to clean it up for public consumption. If anyone is interested, let me know.