SmallSockets with Nu
Last week Colin Barrett suggested that I take a look at SmallSockets, a lightweight Objective-C wrapper for BSD sockets. Today I downloaded the code, built it as a framework, and ran it through a few simple exercises with Nu. Like its name suggests, SmallSockets is simple, but that also means that it’s really easy to use.
Here’s a quick demo.
First, I created a directory called “NuSmallSockets” to use to build the framework. To follow along, copy files from the source distribution into the directory structure below (I’ll give you the Nukefile next).
[Oxygen:~/Desktop/NuSmallSockets] tim% find . . ./Nukefile ./objc ./objc/AbstractSocket.h ./objc/AbstractSocket.m ./objc/Socket.h ./objc/Socket.m
Here’s that Nukefile:
;; source files
(set @m_files (filelist -"^objc/.*\.m$"))
;; framework description
(set @framework "SmallSockets")
(set @framework_identifier "nu.programming.smallsockets")
(set @framework_creator_code "????")
;; libraries
(set @ldflags "-framework Foundation -framework Nu ")
(compilation-tasks)
(framework-tasks)
(task "clobber" => "clean" is
(SH "rm -rf #{@framework_dir}"))
(task "default" => "framework")
With this, you can build the framework by going inside the NuSmallSockets directory and running nuke.
Now let’s use SmallSockets to get an online resource using HTTP. Run the following inside nush:
(load "SmallSockets")
(set socket (Socket socket))
(socket connectToHostName:"www.apple.com" port:80)
(socket writeString:"GET / HTTP/1.0\r\n\r\n")
(set response ((NSMutableData alloc) init))
(while (socket readData:response))
(puts ((NSString alloc) initWithData:response
encoding:NSUTF8StringEncoding))
And for another example, let’s use SmallSockets to serve up a simple greeting, also from within a nush session:
(load "SmallSockets") (set socket ((Socket alloc) init)) (socket listenOnPort:5554) (socket acceptConnection) (socket writeString:"Hello, Nubie\n") (socket close)
To test the server, just type “telnet localhost 5554” inside another terminal session.
Thanks for the recommendation, Colin; and we can all thank Rainer Kupke and Steven Frank for a great little component!
Comments (1) post a reply
Hey, no problem. It served us very well back when Adium had its own protocol implementation (many years ago), and I’ve always been partial to it.