The World's Simplest Distributed Objects Example
With many Cocoa design patterns, getting started is the hardest part. Distributed Objects is a perfect example of this. Run these two scripts to see how simple Distributed Objects can be. It’s all Nu, so there’s no compilation necessary. Be sure to use Nu-0.3.0 or later.
First, here are the two scripts, one for a server and one for a client. The server ‘vends’ an object over a connection to the client. The client gets a proxy for that object and communicates with the server by sending messages to the proxy.
;; server.nu
(set receivePort ((NSSocketPort alloc) initWithTCPPort:8080))
(set connection (NSConnection connectionWithReceivePort:receivePort
sendPort:nil))
(class Server is NSObject
(- (id) name is
((NSString stringWithShellCommand:"hostname") chomp))
(- (void) print:(id) message is
(puts (+ "Client says: " message)))
(- (id) add:(id) x plus:(id) y is
(+ x y))
;; 'oneway' keeps the caller from hanging when the server exits
(- (oneway void) quit is
(puts "Exiting.")
((NSApplication sharedApplication) terminate:0)))
(set server ((Server alloc) init))
(connection setRootObject:server)
(puts "running server")
((NSRunLoop mainRunLoop) run)
;; client.nu
(set sendPort ((NSSocketPort alloc)
initRemoteWithTCPPort:8080
host:"localhost"))
(set connection (NSConnection connectionWithReceivePort:nil
sendPort:sendPort))
(set proxy (connection rootProxy))
(puts (+ "Connected to " (proxy name)))
(proxy print:"I know your name! It is #{(proxy name)}")
(set sum (proxy add:2 plus:2))
(proxy print:"You say that 2 plus 2 is #{sum}")
(proxy quit)
(puts "Finished")
Now in the terminal run the following:
% nush server.nu running server
The server is now waiting for client connections. Open another terminal window and run this:
% nush client.nu Connected to Nubie.local Finished
Back in the terminal where you ran the server, you should see this:
% nush server.nu running server Client says: I know your name! It is Nubie.local Client says: You say that 2 plus 2 is 4 Exiting.
Comments (0) post a reply