Understand from the start that I have forgotten more about TCP port programming than many people ever get to know. I’m not joking, either; I don’t remember large APIs at all well, and have always relied on decent documentation to keep it all together. Liz and I sometimes remark that my modus operandi is that I am extremely good at deducing things, but awful at remembering anything.
In the early 90s (probably ’93), I wrote the core communication mechanism of a Reuters feed distribution system, using a copy of Stevens (probably Advanced Unix Programming, I don’t remember). Since then I have written a few similar but smaller port handlers, but nothing recently.
So, I approach a project to make a handler for the management interface of Asterisk (a very good portable phone switchboard application). I imagine that I can just look up a couple of classes in the Cocoa docs, and get started. I’m sorry, it doesn’t work that way. Check out the documentation for NSPort, which leads you to NSSocketPort; they sound like generic port handlers – but they aren’t. Spotlight on NSSocketPort only finds discussions on the Omni macosx-dev list, which is ominous; it turns out that these two classes are poorly named low level components for Distributed Objects – which is great, but not what I want.
At the moment, it looks like I am forced to choose between using CFSocket, or the basic BSD socket() call, with an NSFileHandle to manage it. I have also found a link to a project called smallsockets; this is a wrapper on BSD sockets. CFSocket is intended to push socket requests into the Run Loop for processing, which avoids the need to write multi-threaded code. If you are interesting in pursuing this course, look in the documentation for CFNetwork to get the overview.
CFSocket is in 10.0, but luckily it has a Cocoa wrapper class, NSStream (although actually it is a wrapper for CFStream), which is however only in 10.3 and above. So that looks like the one to use.
The Programming Topic in the documentation on Streams covers the basic code set up very well, and a test app mostly copied from there works very well as a pseudo telnet client. If you want to write a server, you need to wait for connections, which the NSStreams won’t do, so you have to directly program CFSocket for that. There’s a decent example here (you’ll will have to scroll down to “Source Code” to find the files).
Example code to come, once I write it.
Post a Comment