poctek
poctek

Reputation: 256

Simple HTTP server in Ruby

I'm building a simple HTTP server and have some problems with processing POST requests. Here's the method to create it:

def make_post_request
    puts "Enter the name: "
    name = gets.chomp
    puts "Enter the email: "
    email = gets.chomp

    data = { person: { name: name, email: email } }
    puts data.to_json

    request = "POST /thanks.html HTTP/1.0\nContent-Length: #{data.to_s.length}\r\n\r\n#{data.to_json}"

    return request
end

And here's the server code (not full):

    request = ""

    while line = client.gets
        request << line.chomp
    end

The trouble is that the server doesn't receive the part that comes after "\r\n\r\n", what's wrong in my code?

Upvotes: 1

Views: 822

Answers (1)

matt
matt

Reputation: 79743

It’s not clear from your code exactly what you are doing, but I suspect your problem is that you are relying on gets, which will try and return a full line from the IO object. This means that it will keep blocking waiting for a newline character from the socket (or for it to be closed).

Since your data doesn’t end with a newline, and the client is likely waiting for a response (so doesn’t close the connection), the server is waiting for the newline that never comes.

You could just add a \n to the end of the request which might get your code working here, but in general parsing HTTP messages with bodies is a little trickier than that. The basic approach is to parse the headers and extract the content-length, and then you can read that many bytes from the body and you will know you have reached the end of the message. Of course this gets much more complicated if you start to consider things like chunked transfer encoding.

Upvotes: 1

Related Questions