pkhamre
pkhamre

Reputation: 371

EventMachine::HttpRequest and Keep-alive connection

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

Upvotes: 2

Views: 1646

Answers (2)

Martin Konecny
Martin Konecny

Reputation: 59571

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.

Upvotes: 0

pkhamre
pkhamre

Reputation: 371

I solved my problem by using EM-Synchrony

gem install em-synchrony

With this gem installed, I could use the following code to get the code work as I expected.

request_options = {
  :body => " ",
  :keepalive => true,
  :head => {
    'content-type' => 'application/json',
    'accept' => 'application/json',
    'Accept-Encoding' => 'gzip,deflate,sdch'
  }
}

EM.synchrony do
  request_options[:path] = '/default/path'

  conn = EM::HttpRequest.new 'https://www.example.com'

  req1 = conn.post request_options
  doc = JSON.parse req1.response

  # do stuff with doc

  request_options[:body] = 'post-data'
  request_options[:path] = '/new/path'

  req2 = conn.post request_options
  puts req2.response

  EM.stop
end

I guess I was just confused about they way EM.run does asynchronous requests and di.

Upvotes: 3

Related Questions