Snippets
Code Snippets
Put your interesting code snippets here. Please include a description of what is special about said snippet.
You can add code highlighting as follows:
{{{
#!ruby
def hello_world
puts "hi"
end
}}}
results in
def hello_world puts "hi" end
Safe run in any circumstances
module EventMachine def EventMachine::safe_run(background = nil, &block) if EM::reactor_running? # Attention: here we loose the ability to catch # immediate connection errors. EM::next_tick(&block) sleep unless background # this blocks the thread as it was inside a reactor else if background $em_reactor_thread = Thread.new do EM::run(&block) end else EM::run(&block) end end end end
Usage:
EM::safe_run(:background) do EM::start_server(host, port, server_klass) EM::connect(host, port, client_klass) end
Use this snippet if you'd like to design your library in a way compatible with different apps: both event-driven and threaded.
Writing out to clients before Exit
Let connections finish their work before stopping EM for good.
class Server attr_accessor :connections def initialize @connections = [] # ... end def start @signature = EventMachine.start_server('0.0.0.0', 3000, Connection) do |con| con.server = self end end def stop EventMachine.stop_server(@signature) unless wait_for_connections_and_stop # Still some connections running, schedule a check later EventMachine.add_periodic_timer(1) { wait_for_connections_and_stop } end end def wait_for_connections_and_stop if @connections.empty? EventMachine.stop true else puts "Waiting for #{@connections.size} connection(s) to finish ..." false end end end class Connection attr_accessor :server # ... def unbind server.connections.delete(self) end end
Start a server on an assigned port
available on trunk currently
require ‘socket’
EM.run {
srvr = EM.start_server “0.0.0.0”, 0
p Socket.unpack_sockaddr_in( EM.get_sockname( srvr ))
}
More can be found here.
