By Kevin Conner. See kconner.com.
KCSession attempts to simplify the task of inter-app communication by stitching together Bonjour, sockets, streams, and a simple message format.
I built this set of classes while creating a Mac level editor for my iOS game. I use this code to deliver new versions of game levels over wifi while I edit them. You can use this to set up connections and pass serializable Cocoa objects, without having to worry about servers and sockets and ports.
The only requirement is that the objects you send must be serializable with
NSKeyedArchiver. If you want to use JSON instead of Cocoa objects, that's fine:
NSStrings are serializable with
NSKeyedArchiver. You can write your JSON into a string, send the string using
KCSession, and then parse it on the receiving end.
KCSession uses ARC and works with iOS 5 and/or OS X Lion.
- Make a Bonjour service type string such as
- Create a
KCSessionServerwith that type. It will publish itself on Bonjour. Read KCSessionServer.h for details.
- On the client, search for that type with a
NSNetServiceBrowser. It will give you an
NSNetServicefor the server.
- Create a
NSNetServiceyou found. Read KCNetServiceSession.h for details.
At this point, both the server and the client will have an object inheriting from
KCSession. These are the two ends of the connecton.
KCSession class and its delegate handle message passing. Read KCSession.h for details.
- To send messages, use
-sendMessageWithOpcode:object:. Try a test message with opcode
1and a string.
- To receive messages, implement
- Make an enumeration for the kinds of messages you will send and receive. These are your opcodes.
- Each message can also include a Cocoa object, or nil. Make sure your objects are serializable with
In the server's case, the server itself receives
-session:didReceiveMessageWithOpcode:object: and notifies its delegate.
The server can also broadcast a message to every connected client using
KCSession was built to support my game development cycle and I'm not using it in any production products. So:
- It's not well-tested.
- Message processing should all be done asynchronously on the main thread, but in the server's case, writes are currently synchronous.
- iOS can run a server, but only on IPv4 currently. I need to revisit the
KCSessionServerand add IPv6 support, or just wait for
NSSocketPortto be included in iOS.