eventmachine 实例

require 'eventmachine'
require 'em-http'
require 'fiber'

EventMachine.run do
  page = EventMachine::HttpRequest.new('http://michael-roshen.iteye.com/').get
  page.errback{p "baidu is down! terminate?"}
  page.callback{
    about = EventMachine::HttpRequest.new("http://michael-roshen.iteye.com/blog/2208541").get
    about.callback{ p "callback nesting, ad infinium" }
    about.errback{ p "error-handling code" }
    EventMachine.stop
  }
end

def async_fetch(url)
  f = Fiber.current
  puts f
  http = EventMachine::HttpRequest.new(url).get :timeout => 10
  http.callback { f.resume(http); p "callback..."}
  http.errback { f.resume(http) ; p "errback..."}

  return Fiber.yield
end

EventMachine.run do
  Fiber.new{
    page = async_fetch("http://michael-roshen.iteye.com/")
    puts "fetched page 1: #{page.response_header.status}"
    page = async_fetch("http://michael-roshen.iteye.com/blog/2208541")
    puts "fetched page 2: #{page.response_header.status}"
    EventMachine.stop
  }.resume
end



require 'eventmachine'
require 'em-synchrony'
require 'em-synchrony/em-http'


EventMachine.synchrony do
  page = EventMachine::HttpRequest.new("http://michael-roshen.iteye.com/").get
  p "look ma! no callbacks! fetched page :#{page}"
  EventMachine.stop
end

你可能感兴趣的:(fiber,eventmachine)