响应Eventmachine中的HTTP请求

时间:2013-08-14 13:40:39

标签: ruby http eventmachine

我有一个非常简单的服务器用于集成测试,使用eventmachine构建:

EM.run do
    EM::start_server(server, port, HttpRecipient)    
end

我可以接收HTTP请求并解析它们:

class HttpRecipient < EM::Connection

  def initialize
    @@stored = ''
  end

  # Data is received in chunks, so here we wait until we've got a full web request before
  # calling spool.
  def receive_data(data)
    @@stored << data
    begin
      spool(@@stored)
      EM.stop
    rescue WEBrick::HTTPStatus::BadRequest
      #Not received a complete request yet
    end
  end

  def spool(data)
      #Parse the request
      req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
      req.parse(StringIO.new(@@stored))
      #Send a response, e.g. HTTP OK
  end
end

问题是,如何发送回复? Eventmachine提供send_data用于发送响应,但这不理解http。同样有em-http-request  用于发送请求的模块,但这并不能显示它能够生成响应。

我可以手动生成HTTP消息然后使用send_data发送它们,但是我想知道是否有一种干净的方式来使用现有的http库,或者内置到eventmachine的功能?

1 个答案:

答案 0 :(得分:2)

如果你想要一些简单的东西,那么使用Thin或Rainbows。它在内部使用Eventmachine并提供Rack接口支持。

# config.ru
http_server = proc do |env|
  response = "Hello World!"
  [200, {"Connection" => "close", "Content-Length" => response.bytesize.to_s}, [response]]
end
run http_server

然后

>> thin start -R config.ru

UPD。

如果您需要服务器并行运行,您可以在线程

中运行它
require 'thin'
class ThreadedServer
  def initialize(*args)
    @server = Thin::Server.new(*args)
  end

  def start
    @thread = Thread.start do
      @server.start
    end
  end

  def stop
    @server.stop
    if @thread
      @thread.join
      @thread = nil
    end
  end
end

http_server = proc do |env|
  response = "Hello World!"
  [200, {"Connection" => "close", "Content-Length" => response.bytesize.to_s}, [response]]
end
server = ThreadedServer.new http_server
server.start
# Some job with server
server.stop
# Server is down