Sockets in Cocoa
After brushes with network programming in .NET
(the System.Net.Sockets namespace) and Java (the java.net package), I assumed
that Apple's Cocoa framework would also have nice abstractions for working with
raw sockets. So far this does not appear to be the case...
Cocoa's NSSocketPort seemed like a good place to
start, but apparently the name of this class is misleading. Rather than an
Objective-C wrapper for BSD sockets, it turns out that NSSocketPort is used for
Cocoa's distributed objects. These are something I haven't played with yet; they
have no relevance to my current project because the server side of things isn't
Cocoa.While there are several
third-party solutions available (see this
nice summary from Stepwise), I decided to take the time to learn a bit
about BSD socket programming from the ground up and try to apply that knowledge
to my little Cocoa project. If nothing else, I figured that the knowledge gained
would help me choose one of the third party
frameworks.The best web-based resource
I found for aspiring network programmers is Beej's Guide to Network
Programming, which not only covers the basics, but proves that
technical writing needn't bore one to tears. Most any programmer familiar with
the C language should have no trouble reading through this
guide.A reinforcement and review of
topics from Beej's Guide can be found in Micheal
Beam's Networking and the BSD Sockets API article on O'Reilly's MacDevCenter, which is part 2 of a
3 part article (part 1 deals with using Rendezvous for service discovery). In
the followup article titled Networking
in Cocoa, Mike begins to put an Objective-C spin on the topic using
the NSFileHandle class of Cocoa's Foundation framework. According to Apple's
overview of NSFileHandle, "It
provides the only Foundation object that can read and write to communications
channels such as those implemented by sockets, pipes, and
devices."For my current need to
create a TCP client, NSFileHandle will get me there, but it's worth mentioning
that NSFileHandle has its limitations. From that same page of Apple's
documentation, we find that
"NSFileHandle currently handles only
communication through stream-type sockets. If you want to use datagrams or other
types of sockets, you must create and manage the connection using native system
routines."Time to drop a note in
Apple's suggestion
box, I guess...
Posted: Tue - December 28, 2004 at 05:07 PM