简体   繁体   English

没有网络的Ruby HTTP服务器

[英]Ruby HTTP server without networking

I am trying to add an HTTP server to an existing Ruby application. 我试图将HTTP服务器添加到现有的Ruby应用程序。 The application is based around a select loop, and I want to handle incoming HTTP requests there too (it is important to process the requests in the same thread, or I have to jump through hoops to marshal them there). 该应用程序基于一个select循环,我也想在那里处理传入的HTTP请求(在同一个线程中处理请求很重要,否则我必须跳过循环将其封送在那里)。

Ruby has plenty of solutions for standalone HTTP servers, but I can't seem to find a library which implements an HTTP server on an existing socket. Ruby为独立的HTTP服务器提供了许多解决方案,但是我似乎找不到在现有套接字上实现HTTP服务器的库。 I don't want the HTTP library to open a port and wait, I want to feed it sockets. 我不希望HTTP库打开端口并等待,我想向其提供套接字。

The basic logic I'm looking for is this: 我正在寻找的基本逻辑是:

handler = SomeHTTPParsingLibrary.new
# set up handler callbacks, etc on handler...

while socket = get_incoming_connection()
    handler.handle_request(socket)
end

Are there any existing Ruby libraries that can work like this? 是否有现有的Ruby库可以像这样工作? HTTP is a simple enough protocol, but there are enough irritating details involved (I need cookies, basic auth, etc) that I'd rather not roll my own. HTTP是一个足够简单的协议,但是涉及很多令人讨厌的细节(我需要Cookie,基本身份验证等),而我不想自己动手。

您可能需要HTTPParser找出要调用的方法,但是我建议从mongrel中尝试HTTPParser类。

A quick glance through the code in httprequest.rb (webrick - from ruby stdlib) seems like it might suit your purpose. 快速浏览httprequest.rb的代码( httprequest.rb来自ruby stdlib)似乎很适合您的目的。

A WEBrick::HTTPRequest object is able to accept a socket as an argument to its parse() method. WEBrick::HTTPRequest对象能够接受套接字作为其parse()方法的参数。 It will then block, and return when the request object has been fully populated with the incoming HTTP request. 然后它将阻塞,并在请求对象已完全用传入的HTTP请求填充时返回。

eg: 例如:

    res = HTTPResponse.new(@config)
    req = HTTPRequest.new(@config)

    # some code to "select" a socket goes here

    # sock is active, hand it over to the req object for reading.
    req.parse(sock)
    res.request_method = req.request_method

Of course, this assumes that this thread will block will the current request handling is complete. 当然,这假设此线程将阻塞当前请求的处理完成。

OTOH, something like tmm1/http_parser.rb might also fit your needs, but sacrifice other things (like handling cookies) in favor of speed. OTOH,诸如tmm1/http_parser.rb类的tmm1/http_parser.rb也可能满足您的需求,但为了提高速度而牺牲了其他内容(例如处理Cookie)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM