Sha256: 41861fae0f4604e0991addfaac39d8c1f92bd10996de7e1a4cbf07519b6767e8

Contents?: true

Size: 1.08 KB

Versions: 2

Compression:

Stored size: 1.08 KB

Contents

$: << 'lib' << '../lib'

require 'ZMachine'
require 'z-http'
require 'fiber'

# Using Fibers in Ruby 1.9 to simulate blocking IO / IO scheduling
# while using the async ZMachine API's

def async_fetch(url)
  f = Fiber.current
  http = ZMachine::HttpRequest.new(url, :connect_timeout => 10, :inactivity_timeout => 20).get

  http.callback { f.resume(http) }
  http.errback  { f.resume(http) }

  Fiber.yield

  if http.error
    p [:HTTP_ERROR, http.error]
  end

  http
end

ZMachine.run do
  Fiber.new{

    puts "Setting up HTTP request #1"
    data = async_fetch('http://0.0.0.0/')
    puts "Fetched page #1: #{data.response_header.status}"

    puts "Setting up HTTP request #2"
    data = async_fetch('http://www.yahoo.com/')
    puts "Fetched page #2: #{data.response_header.status}"

    puts "Setting up HTTP request #3"
    data = async_fetch('http://non-existing.domain/')
    puts "Fetched page #3: #{data.response_header.status}"

    ZMachine.stop
  }.resume
end

puts "Done"

#  Setting up HTTP request #1
#  Fetched page #1: 302
#  Setting up HTTP request #2
#  Fetched page #2: 200
#  Done

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
z-http-request-0.2.0 examples/fibered-http.rb
z-http-request-0.1.0 examples/fibered-http.rb