A first dRuby server and client
Two short scripts: a server that publishes an object with DRb.start_service and a client that calls it through DRbObject.new_with_uri.
Updated
A dRuby server is a Ruby script that calls DRb.start_service with a URI and an object. A client is a script that calls DRbObject.new_with_uri with the same URI and then uses the result like a local object. Here are both, complete.
The server
# server.rb
require 'drb/drb'
class Clock
def now
Time.now
end
def greet(name)
"Hello, #{name}"
end
end
DRb.start_service('druby://localhost:8787', Clock.new)
puts "Serving at #{DRb.uri}"
DRb.thread.join
Three things happen here:
Clock.newbecomes the front object: the object that answers calls arriving at this URI.DRb.start_service(uri, front)opens the socket and starts accepting connections in a background thread.DRb.thread.joinkeeps the script alive. Without it the main thread would reach the end of the file and the process would exit. More on that in threads and keeping a server alive.
Binding to localhost means only programs on the same machine can connect, which is the right default.
The client
# client.rb
require 'drb/drb'
DRb.start_service
clock = DRbObject.new_with_uri('druby://localhost:8787')
puts clock.now
puts clock.greet('Ruby')
Run ruby server.rb in one terminal and ruby client.rb in another. The client prints the server's current time and a greeting.
DRbObject.new_with_uri does not connect to anything. It only builds a proxy that remembers the URI. The connection is made on the first method call, so a wrong URI or a stopped server shows up there, as a DRb::DRbConnError.
begin
puts clock.now
rescue DRb::DRbConnError => e
warn "Could not reach the server: #{e.message}"
end
Why the client calls DRb.start_service
This client would work without the DRb.start_service line, because it only sends and receives simple values. It is still a good habit to include it. As soon as you pass a block or an object that travels by reference, the server needs to call back into the client, and that requires a running service on the client side. See callbacks and blocks.
What can be called
Only public methods of the front object can be called remotely. Arguments and return values must either be marshalable (strings, numbers, symbols, arrays, hashes, Time, and most plain objects) or travel by reference. Time.now above is marshaled on the server and rebuilt as a Time in the client. The rules are on pass by value and pass by reference.
Before you change the address
Changing localhost to a public address lets anyone who can reach the port call into your process. Read why dRuby must not face untrusted networks first.