2

我有一个非常简单的服务器用于集成测试,使用 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 内置的功能?

4

1 回答 1

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
于 2013-08-14T15:33:42.587 回答