我有一个基本的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数据?
感谢您的帮助。
答案 0 :(得分:4)
可以在不增加太多服务器的情况下执行此操作:
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
}
答案 1 :(得分:2)
对于非常简单的应用程序,您可能希望使用Sinatra编写一些内容,这与您可以获得的内容基本相同。
post('/') do
# Do stuff with post data stored in params
puts params[:example]
end
然后你可以将它放在Rack脚本config.ru
中,并使用任何符合Rack的服务器轻松托管它。
答案 2 :(得分:0)
client.read(length) # length is length of request header content