General Introduction
The Reactor
The reactor must be in control of the main ruby thread. Generally you wrap your entire program inside of the run block:
EventMachine::run do
EventMachine::start_server ...
end
The end of the blocks execution will spin up the reactor, this will not return until something in the runtime loop calls EventMachine::stop. . The rest of the code in below assumes being run inside a run block.
Connections
Can be defined a few ways:
Blocks/Procs:
EventMachine::connect '127.0.0.1', 22 do |c|
def c.receive_data(data)
p data
end
end
Modules:
module Echo
def receive_data(data)
p data
end
end
EventMachine::connect '127.0.0.1', 22, Echo
Classes:
class Echo < EventMachine::Connection
def initialize(*args)
super
# stuff here...
end
def receive_data(data)
p data
end
end
EventMachine::connect '127.0.0.1', 22, Echo
A lot of people settle for modules, this leaves flexibility in the future.
Timers
Again, Blocks/Procs, Instances, Subclasses
Block:
time = Time.now
EventMachine::add_timer(1) do
puts "hello one second from #{time}!"
end
Instances:
EventMachine::Timer.new(1, proc { puts 'hi' })
- Instances can use blocks too of course...
- Scheduled as soon as the reactor is unblocked, and in strict order of definition.
- There's add_periodic_timer too..
