You can create an interface in the server, so when the client connects to it, can change some state in the server (pass it's own object).
See this code:
server.rb
require 'drb'
class Server
attr_accessor :object
def initialize()
@object = {:id => 'from server side'}
end
end
server = Server.new
DRb.start_service('druby://localhost:1992', server)
puts DRb.uri
begin
DRb.thread.join
rescue Exception
Process.kill("TERM", Process.pid)
end
client.rb
require 'drb'
@server = DRbObject.new(nil, "druby://localhost:1992")
DRb.start_service
puts @server.object
@server.object = {:id => "from client side"}
puts @server.object
the output is:
{:id=>"from server side"}
{:id=>"from client side"}
Also, DRuby
implements the observer pattern, so you can make your server observable including DRb::DRbObservable
module in the class Server. Then you implements the method notify
to notify all the observers, passing objects that can be serializes (including include DRb::DRbUndumped
). In the client side we can add observer to the server and implement the method update to do something with the notification, see this example:
server.rb
require 'drb'
require 'drb/observer'
class Server
include DRb::DRbObservable
attr_accessor :object
def initialize()
@object = {:id => 'from server side'}
end
def do_something
notify(Message.new("this is a notification"), Message.new("other notification"))
end
def notify(*args)
changed
notify_observers(*args)
end
class Message
include DRb::DRbUndumped
attr_reader :message
def initialize(message)
@message = message
end
end
end
server = Server.new
DRb.start_service('druby://localhost:1992', server)
puts DRb.uri
begin
DRb.thread.join
rescue Exception
Process.kill("TERM", Process.pid)
end
client.rb
require 'drb'
class MyObserver
include DRbUndumped
def update(*notifications)
puts "checking notifications ..."
notifications.each do |n|
puts n.message
end
end
end
@server = DRbObject.new(nil, "druby://localhost:1992")
DRb.start_service
@server.add_observer(MyObserver.new)
puts @server.object
@server.object = {:id => "from client side"}
puts @server.object
@server.do_something
the output is:
{:id=>"from server side"}
{:id=>"from client side"}
checking notifications ...
this is a notification
other notification