%(entry-title) Advanced Stuff %
Each worker comes with an Event loop of its own and can potentially do lots of fancy stuff. Two noteworthy methods are:
connect(ip,port,Handler)
start_server(ip,port,Handler)
If you are familiar with the EventMachine or Twisted style of network programming, the above methods allow you to
start tcp servers inside your workers or let you connect to external tcp servers. For Each accepted client or
connected socket, an instance of Handler class would be created and integrated with main event loop.
This can be used for worker to worker communication between backgroundrb servers running on two machines.
p(sub-title). @BackgrounDRb::MetaWorker#connect@ :
@connect@ lets you connect to an external TCP Server and integrates the connection within reactor loop
of worker. For example:
class TimeClient
def receive_data(p_data)
worker.get_external_data(p_data)
end
def post_init
p "***************** : connection completed"
end
end
class FooWorker < BackgrounDRb::MetaWorker
set_worker_name :foo_worker
def create(args = nil)
external_connection = nil
connect("localhost",11009,TimeClient) { |conn| external_connection = conn }
end
def get_external_data(p_data)
puts "And external data is : #{p_data}"
end
end
p(sub-title). @BackgrounDRb::MetaWorker#start_server@ :
Above method allows you to start a tcp server from your worker, all the accepted connections are integrated with event loop of worker.
class TimeServer
def receive_data(p_data)
end
def post_init
add_periodic_timer(2) { say_hello_world }
end
def connection_completed
end
def say_hello_world
p "***************** : invoking hello world #{Time.now}"
send_data("Hello World\n")
end
end
class ServerWorker < BackgrounDRb::MetaWorker
set_worker_name :server_worker
def create(args = nil)
# start the server when worker starts
start_server("0.0.0.0",11009,TimeServer) do |client_connection|
client_connection.say_hello_world
end
end
end