我有一个基本的 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
}
Run Code Online (Sandbox Code Playgroud)
我将如何捕获 POST 数据?
谢谢你的帮助。
小智 7
可以在不向服务器添加太多内容的情况下执行此操作:
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
}
Run Code Online (Sandbox Code Playgroud)
对于非常简单的应用程序,您可能想使用Sinatra编写一些尽可能基本的内容。
post('/') do
# Do stuff with post data stored in params
puts params[:example]
end
Run Code Online (Sandbox Code Playgroud)
然后,您可以将其粘贴到 Rack 脚本中,config.ru并使用任何兼容 Rack 的服务器轻松托管它。