Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Practical EventMachine

febuiles
October 25, 2014

Practical EventMachine

EventMachine (EM) is an event-driven concurrency library for Ruby, akin to Python's Twisted or Node.js. In this talk we'll explore some of the patterns and abstractions behind EM, how we can apply those ideas to our applications and how the library has been used by companies like GitHub and Heroku.

febuiles

October 25, 2014
Tweet

More Decks by febuiles

Other Decks in Programming

Transcript

  1. i/o

  2. server = TCPServer.new(1337) ! while client = server.accept message =

    client.readline client.write "> #{message}" client.close end
  3. server = TCPServer.new(1337) ! while true Thread.new(server.accept) do |client| message

    = client.readline client.write "> #{message}" client.close end end
  4. Reactor.run { on(:receive) do |msg| return if invalid_message(msg)? ! device

    = Device.find(msg.device_id) device.update(position: msg.position) end }
  5. Reactor.run { on(:receive) do |msg| return if invalid_message(msg)? ! device

    = Device.find(msg.device_id) device.update(position: msg.position) end }
  6. ?

  7. module Echo def receive_data(message) send_data "> #{message}" end end !

    EM.run { EM.start_server "0.0.0.0", 1337, Echo }
  8. module Echo def post_init puts "Client connected" end ! def

    receive_data(message) send_data "> #{message}" end ! def unbind puts "Client disconnected" end end ! EM.run { EM.start_server "0.0.0.0", 1337, Echo }
  9. server = AsyncTCPServer.new("0.0.0.0", 1337) ! server.on(:accept) { message = client.async_read

    ! message.on(:ready) { client.write "> #{message}" client.close } } ! server.on(:connect) { puts "Client connected" } ! server.on(:disconnect) { puts "Client disconnected" }
  10. module Echo def receive_data(data) message = parse_data(data) return if invalid_message(message)?

    ! device = Device.find(message.device_id) device.update(position: message.position) send_data :updated end end ! EM.run { EM.start_server "0.0.0.0", 1337, Echo }
  11. module Echo def receive_data(data) message = parse_data(data) return if invalid_message(message)?

    ! device = Device.find(message.device_id) device.update(position: message.position) send_data :updated end end ! EM.run { EM.start_server "0.0.0.0", 1337, Echo }
  12. module Graham def receive_data(number) calculate = proc { graham(number) }

    ! report = proc { |result| send_data(result) } ! EM.defer(calculate, report) end end
  13. Credits Federico’s illustration: Pablo Pérez Nuclear cooling tower: Jonathan Brennan

    Some code samples: Aman Gupta & Jeremy Cheung Unicorn diagram: GitHub The rest: Wikipedia