一个简单的 HTTP Server 例子
require 'eventmachine'
require 'em-http-server'
class HTTPHandler < EM::HttpServer::Server
  # 请求从这里开始执行
  def process_http_request
    @http # 包含所有 http headers 的 hash
    @http_content # http body
    # 构造 http response
    response = EventMachine::DelegatedHttpResponse.new(self)
    response.status = 200
    response.content = 'hello, world!'
    response.send_response
  end
  # 请求发生异常时的回调方法
  def http_request_errback e
    puts "#{e.backtrace.shift}: #{e.message} (#{e.class})"
    puts e.backtrace.map{|line| "\tfrom #{line}"}
  end
end
EM.run do
  # hit Control + C to stop
  Signal.trap("INT")  { EventMachine.stop }
  Signal.trap("TERM") { EventMachine.stop }
  EM.start_server 'localhost', 10000, HTTPHandler
end
请求解析错误时,自定义错误返回信息
在
HTTPHandler中实现http_error_string方法,返回值就是返回信息。
与 EventMachine 的关系
EM::HttpServer::Server<EM::P::HeaderAndContentProtocol<EM::Connection
