123456789_123456789_123456789_123456789_123456789_

The Reactor

The reactor is the core of EventMachine. All of EM’s processing happens in the reactor. Your application will create code that hooks into the reactor, using timers, socket connections or various other means. Typically you’ll wrap your entire application inside an EM#run block.

EventMachine.run do
  EventMachine.start_server #...
end

This block won’t complete until EM#stop is called. The reactor will loop infinitely. All of the examples on this page assume they are being executed inside the reactor.

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' })