简体   繁体   English

Ruby中的简单HTTP服务器

[英]Simple HTTP server in Ruby

I'm building a simple HTTP server and have some problems with processing POST requests. 我正在构建一个简单的HTTP服务器,并且在处理POST请求时遇到一些问题。 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? 问题是服务器没有收到“ \\ r \\ n \\ r \\ n”后面的部分,我的代码有什么问题?

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. 从代码中还不清楚您正在做什么,但是我怀疑您的问题是您依赖gets ,它将尝试从IO对象返回整行。 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. 您可以在请求的末尾添加一个\\n ,这可能会使您的代码在这里工作,但是通常来说,使用主体解析HTTP消息比这要复杂一些。 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. 当然,如果您开始考虑分块传输编码之类的话,这将变得更加复杂。

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

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