Skip to content
This repository

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

There are a few different ways to define connections, blocks/procs, modules or classes. A lot of people settle for modules, this leaves flexibility in the future.

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

Timers

Again, blocks/procs, instances, subclasses.

Block/Proc

time = Time.now
EventMachine::add_timer(1) do
  puts "hello one second from #{time}!"
end

Instance

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..
Something went wrong with that request. Please try again.