ruby 1.9.3简单GET通过套接字请求独角兽

Evg*_*nii 1 ruby sockets

现在我尝试使用此代码连接到由unicorn创建的套接字

require 'socket'

def foo
  socket = UNIXSocket.new("path_to_socket/tmp/unicorn.sock")

  data = "GET /time HTTP/1.1\n" 
  data << "Connection: Close\n" 
  data << "User-Agent: Mozilla/5.0\n" 
  data << "Accept: */*\n" 
  data << "Content-Type: application/x-www-form-urlencoded\n" 
  data << "\n\r\n\r"

  socket.puts(data)

  while(line = socket.gets) do
    puts line
  end 
end

foo
Run Code Online (Sandbox Code Playgroud)

但总是得到"HTTP/1.1 400错误请求"

拜托,任何人都可以说我做错了吗???

小智 5

使用net/http ...

require "net/http"
require "socket"

sock = Net::BufferedIO.new(UNIXSocket.new("path_to_socket/tmp/unicorn.sock"))
request = Net::HTTP::Get.new("/time")
request.exec(sock, "1.1", "/time")

begin
  response = Net::HTTPResponse.read_new(sock)
end while response.kind_of?(Net::HTTPContinue)
response.reading_body(sock, request.response_body_permitted?) { }

response.body
response.code
Run Code Online (Sandbox Code Playgroud)