Eventmachine HTTP Client

For some reason, this simple example has eluded me for some time. “EventMachine is a library for Ruby, C++, and Java programs. It provides event-driven I/O using the Reactor pattern.” When using Eventmachine, as I often do, asynchronous network calls are key. And often in the word of web services, crawling and scraping most useful clients I write these days deal with HTTP. So here is the most basic example of an HTTP client written using eventmachine:

require 'rubygems'
require 'eventmachine'

EM.run do
  include EM::Protocols
  conn = HttpClient2.connect('simonwex.com', 80)

  req = conn.get('/')
  req.callback do
    p(req.content)
    EM.stop
  end
end