简体   繁体   English

如何使用ruby和tcpserver读取传入的POST Multipart请求中的

[英]How do I read a in incoming POST Multipart request using ruby and tcpserver

I have created a very simple server: 我创建了一个非常简单的服务器:

#!/bin/ruby

require 'socket'

server = TCPServer.open 2000
puts "Listening on port 2000"

loop {
  client = server.accept

  client.puts "HTTP/1.1 200/OK\r\nContent-type:text/html\r\n\r\n"
  response = "My super slim ruby http server"
  client.puts response

  received = client.recv(1024)
  puts received
  puts "\n"

  client.close
}

So far, it serves my purpose, which is to print out the requests that might come from a given client. 到目前为止,它符合我的目的,即打印出可能来自给定客户端的请求。 However, if I use, for example, the following curl command to create a request: 但是,例如,如果我使用以下curl命令创建请求:

curl -F "data=someData" http://localhost:2000

My ruby server only prints out the HTTP headers, but not the body of the request. 我的ruby服务器仅打印出HTTP标头,而不打印请求的正文。

Is there a way to do this? 有没有办法做到这一点?

Looks like you have to call recv again to get the body: 看来您必须再次致电recv才能获得尸体:

#!/bin/ruby

require 'socket'

server = TCPServer.open 2000
puts "Listening on port 2000"

loop {
  client = server.accept

  client.puts "HTTP/1.1 200/OK\r\nContent-type:text/html\r\n\r\n"
  response = "My super slim ruby http server"
  client.puts response

  headers = client.recv(1024)
  headers =~ /Content-Length: (\d+)/ # get content length
  body    = $1 ? client.recv($1.to_i) : '' # <- call again to get body if there is one

  puts headers + body

  client.close
}

Thanks bundacia, I ended up mixing what you sent and some other findings and this is the result: 感谢Bundacia,我最终混合了您发送的内容和其他一些发现,结果如下:

#!/bin/ruby

require 'socket'

server = TCPServer.open 2000
puts "Listening on port 2000"

loop {
client = server.accept

client.puts "HTTP/1.1 200/OK\r\nContent-type:text/xml\r\n\r\n"
response = "My super slim ruby http server"
client.puts response

all_data = []
i = 1024
firstrun = "yes"
while i > 0
    partial_data = client.recv(i)
    if (firstrun == "no")
        i = 0
    end
    if (firstrun == "yes")
        partial_data =~ /Content-Length: (\d+)/ # get content length
        length = $1
        if (nil != length && !length.empty?)
            i = length.to_i
            firstrun = "no"
        end
    end

    all_data << partial_data
end

puts all_data.join()

client.close
}

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

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