EventMachine and looping

六月ゝ 毕业季﹏ 提交于 2019-12-05 09:51:01

The run block you give runs only once. The event loop is not exposed directly to you but is something that's intended to be invisible. Don't confuse the run block with a while loop. It's run once and once only, but it is run while the event loop is executing.

If you want to repeat an operation you need to create some kind of a stack and work through that, with each callback checking the stack if there's more work to do and then issuing another call. EventMachine applications are built using this callback-chaining method.

You will need to implement something like:

def do_stuff(queue, request = nil)
  request ||= queue.pop
  return unless (request)

  conn = EM::Protocols::HttpClient2.connect request.host, 80

  req = conn.get(request.query)
  req.callback { |response|
    p(response.status)
    p(response.headers)
    p(response.content)

    EventMachine.next_tick do
      # This schedules an operation to be performed the next time through
      # the event-loop. Usually this is almost immediate.
      do_stuff(queue)
    end
  }
end   

Inside your event loop you kick of this chain:

EventMachine.run do
  queue = [ ... ] # List of things to do
  do_stuff(queue)
end

You can probably find a more elegant way to implement this once you get a better sense of how EventMachine works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!