Ruby异步网络::HTTP?

Ruby异步网络::HTTP?,ruby,asynchronous,block,net-http,Ruby,Asynchronous,Block,Net Http,Net::HTTP是否支持异步语法 我正在寻找类似下面的代码 在Net::HTTP接收到来自服务器的响应(在这种情况下,error将为nil)或连接到服务器时遇到错误(在这种情况下,response将为nil)之后,将在主线程上调用该块 以下问题提供了答案,但我正在寻找基于块的解决方案 查看eventmachine和emhttp请求gems。与上述代码等效的代码是 require 'rubygems' require 'eventmachine' require 'em-http' HT

Net::HTTP
是否支持异步语法

我正在寻找类似下面的代码

Net::HTTP
接收到来自服务器的响应(在这种情况下,
error
将为
nil
)或连接到服务器时遇到错误(在这种情况下,
response
将为
nil
)之后,将在主线程上调用该块

以下问题提供了答案,但我正在寻找基于块的解决方案


查看
eventmachine
emhttp请求
gems。与上述代码等效的代码是

require 'rubygems'
require 'eventmachine'
require 'em-http'

HTTP_OK = 200

EM.run do
  http = EM::HttpRequest.new('http://example.com').get

  http.errback do
    puts "Connection error: #{http.error}"
    EM.stop
  end

  http.callback do
    if http.response_header.status == HTTP_OK
      puts "Success!"
      puts http.response
    else
      puts "Unexpected status code: #{http.response_header.status}"
    end
    EM.stop
  end
end
有一个很好的例子,就是在网络上使用光纤


编辑:我也建议阅读

这是一个很好的例子,但测试双重否定似乎不是一个好主意。测试
==HTTP_OK
,然后测试
else
会更容易理解。现在成功的条件是“如果不好”。@tadman谢谢!你是对的,修复了这个。我想我尽量反映op的代码结构。
require 'rubygems'
require 'eventmachine'
require 'em-http'

HTTP_OK = 200

EM.run do
  http = EM::HttpRequest.new('http://example.com').get

  http.errback do
    puts "Connection error: #{http.error}"
    EM.stop
  end

  http.callback do
    if http.response_header.status == HTTP_OK
      puts "Success!"
      puts http.response
    else
      puts "Unexpected status code: #{http.response_header.status}"
    end
    EM.stop
  end
end