这是我的代码:
EventMachine.run {
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)
}
}
Run Code Online (Sandbox Code Playgroud)
回调触发,也就是说,我得到状态的字符串输出等.
但我想要它做的是触发回调,然后重复.我计划实施更多逻辑,例如每次调整URL,但就目前而言,我只想要:
我对这种模式的理解是,该循环中的所有内容都会触发,然后返回,然后一直持续到我执行为止EM.stop.
现在,它检索URL数据,似乎挂起了.
我需要做某种回报才能继续吗?它为什么悬挂,而不是一遍又一遍地循环?
如果我用循环包围整个上面的代码块...结束它按预期工作..这是实现这个的正确方法吗?我想我很困惑,因为我认为一切都在EM.run重复时完成.
您给出的块run仅运行一次。事件循环不会直接暴露给您,但它是不可见的。不要将run块与while循环混淆。它只运行一次,但在事件循环执行时运行。
如果您想重复某个操作,则需要创建某种堆栈并完成该操作,每个回调都会检查堆栈是否还有更多工作要做,然后发出另一个调用。EventMachine 应用程序是使用此回调链接方法构建的。
您将需要实现类似的东西:
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
Run Code Online (Sandbox Code Playgroud)
在你的事件循环中,你启动了这个链:
EventMachine.run do
queue = [ ... ] # List of things to do
do_stuff(queue)
end
Run Code Online (Sandbox Code Playgroud)
一旦您更好地了解了 EventMachine 的工作原理,您可能会找到一种更优雅的方法来实现这一点。