gpt4 book ai didi

ruby - 如何从简单的 Ruby 服务器捕获 POST 数据

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:54 25 4
gpt4 key购买 nike

我有一个基本的 Ruby 服务器,我想监听一个特定的端口,读取传入的 POST 数据,然后做......

我有这个:

require 'socket'               # Get sockets from stdlib

server = TCPServer.open(2000) # Socket to listen on port 2000
loop { # Servers run forever
client = server.accept # Wait for a client to connect
client.puts(Time.now.ctime) # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close # Disconnect from the client
}

我将如何捕获 POST 数据?

感谢您的帮助。

最佳答案

可以在不向服务器添加太多内容的情况下执行此操作:

require 'socket'               # Get sockets from stdlib

server = TCPServer.open(2000) # Socket to listen on port 2000
loop { # Servers run forever
client = server.accept # Wait for a client to connect
method, path = client.gets.split # In this case, method = "POST" and path = "/"
headers = {}
while line = client.gets.split(' ', 2) # Collect HTTP headers
break if line[0] == "" # Blank line means no more headers
headers[line[0].chop] = line[1].strip # Hash headers by type
end
data = client.read(headers["Content-Length"].to_i) # Read the POST data as specified in the header

puts data # Do what you want with the POST data

client.puts(Time.now.ctime) # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close # Disconnect from the client
}

关于ruby - 如何从简单的 Ruby 服务器捕获 POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com