Skip to content
tjeden edited this page Oct 28, 2010 · 18 revisions

Simple example

First of all, you need to expose an object over the network in your first process :

Core/Server process :

require 'brb'

class ExposedCoreObject
  def simple_api_method
    return 'OK'
  end
end

EM::run do
  BrB::Service.start_service(:object => ExposedCoreObject.new,
    :host => 'localhost', :port => 5555)
end

Then, a second process will connect to the core and interact with it :

Simple client process :

require 'brb'

# Connecting to the core server, retrieving its interface object : core
core = BrB::Tunnel.create(nil, "brb://localhost:5555")

# Calling a non-blocking method 10 times on the distant core server
10.times do
  core.simple_api_method # Do not wait for response
end

# Calling a non-blocking method with a callback in order to
# get the return value at any time
core.simple_api_method do |r|
  puts " > API response in the callback trigger block : #{r}"
end

# Calling a blocking method with _block on the distant core server
r = core.simple_api_method_block # This call will wait forever for the return ...
puts " > API response : #{r}"

# Our job is over, stop Event Machine
EM.stop

Get connections events

When a client connects or leaves a BrB tunnel, an event is called :

BrB::Service.start_service(:object => ExposedCoreObject.new, :host => 'localhost', :port => 5555) do |type, tunnel|
  if type == :register
    # A new tunnel has been opened, you can call method directly on the tunnel
  elsif type == :unregister
    # A tunnel has been closed, you need to handle it
  end
end

# Same things happen with tunnel : 
BrB::Tunnel.create(nil, "brb://localhost:5555") do |type, tunnel|
  # Handle connection and disconnection here
end

There are currently two types of events: :register and :unregister

Example with both side exposition

Now that we can catch events, we can use them to start communicating between both of our distant processes.

First, when the client creates a tunnel, it expose an object just like the core does :

core = BrB::Tunnel.create(ExposedClientObject.new, "brb://localhost:5555")

Now, when the core gets a :register event, it can directly use the associated tunnel method by calling it.

BrB::Service.instance.start_service(:object => ExposedCoreObject.new, :host  => 'localhost', :port => 5555)  do  |type, tunnel|
  # Get alerted that a new connection has been made :
  if type == :register
    tunnel.any_method_call(params)
  end
end

Tips

  • “EM” in examples is eventmachine.
  • You can find more examples or sample of code in the examples folder of the project.
Clone this wiki locally