当前位置: 动力学知识库 > 问答 > 编程问答 >

Ruby HTTP server without networking

问题描述:

I am trying to add an HTTP server to an existing Ruby application. 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).

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. I don't want the HTTP library to open a port and wait, I want to feed it sockets.

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? 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.

网友答案:

You may have to roll your sleeves up a bit to figure out what methods to call, but I'd suggest trying the HTTPParser class from within mongrel.

网友答案:

A quick glance through the code in httprequest.rb (webrick - from ruby stdlib) seems like it might suit your purpose.

A WEBrick::HTTPRequest object is able to accept a socket as an argument to its parse() method. It will then block, and return when the request object has been fully populated with the incoming HTTP request.

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: