ruby - 在 Eventmachine 中响应 HTTP 请求

标签 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 内置的功能?

最佳答案

如果您想要简单的东西,请使用 Thin 或 Rainbows。内部使用Eventmachine,并提供Rack接口(interface)支持。

# 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

更新。

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

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

关于ruby - 在 Eventmachine 中响应 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18233388/

相关文章:

ruby-on-rails - Rails 加载我的@items n*n 次

python - 奇怪的python请求消息大小

http - 如何在Delphi xe中使用HTTP客户端登录网站

ruby - 是否可以从 Thin/Rack/Sinatra 访问 Ruby EventMachine channel ?

ruby - ruby 中的 openssl 等效命令

ruby-on-rails - Active Record 序列化 attr 丢失字符串编码(可能是 YAML 问题),解决方法?

ruby - 使用 SQL 的 EventMachine 服务器和串口

ruby-on-rails - ruby rails : "cannot load such file" eventmachine

ruby-on-rails - 如何制作不止一个 ruby​​ 类对象?

http - 我应该为 HTTP 基本身份验证使用什么编码?