EventMachine::HttpRequest 和保持连接
我使用以下代码运行几个 HTTP 请求,但第二个请求 (req2) 始终返回 errback。
我在这里遗漏了一些明显的东西吗?
request_options = {
:body => " ",
:keepalive => true,
:head => {
'content-type' => 'application/json',
'accept' => 'application/json',
'Accept-Encoding' => 'gzip,deflate,sdch'
}
}
EM.run do
request_options[:path] = '/default/path'
conn = EM::HttpRequest.new 'https://www.example.com'
req1 = conn.post request_options
req1.errback { p 'Uh, oh'; EM.stop }
req1.callback do
doc = JSON.parse req1.response
# do stuff with doc
request_options[:body] = 'post-data'
request_options[:path] = '/new/path'
req2 = conn.post request_options
req2.errback { p 'Uh, oh'; EM.stop }
req2.callback do
puts req2.response
EM.stop
end
end
end
I'm using the following code to run a couple of HTTP requests, but the second request (req2) always returns to errback.
Am I missing something obvious here?
request_options = {
:body => " ",
:keepalive => true,
:head => {
'content-type' => 'application/json',
'accept' => 'application/json',
'Accept-Encoding' => 'gzip,deflate,sdch'
}
}
EM.run do
request_options[:path] = '/default/path'
conn = EM::HttpRequest.new 'https://www.example.com'
req1 = conn.post request_options
req1.errback { p 'Uh, oh'; EM.stop }
req1.callback do
doc = JSON.parse req1.response
# do stuff with doc
request_options[:body] = 'post-data'
request_options[:path] = '/new/path'
req2 = conn.post request_options
req2.errback { p 'Uh, oh'; EM.stop }
req2.callback do
puts req2.response
EM.stop
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通过使用EM-Synchrony解决了我的问题
安装了这个gem后,我可以使用以下代码使代码按我的预期工作。
我想我只是对 EM.run 执行异步请求和 di 的方式感到困惑。
I solved my problem by using EM-Synchrony
With this gem installed, I could use the following code to get the code work as I expected.
I guess I was just confused about they way EM.run does asynchronous requests and di.
您不能在响应回调中使用相同的连接对象。
确保为第二个请求创建新的
EM::HttpRequest.new 'https://www.example.com'
。You can't use the same connection object inside the response callback.
Make sure you create a new
EM::HttpRequest.new 'https://www.example.com'
for the second request.