Reading data from a socket in ruby in a multithreaded environment
I am trying to read an HTTP packet via a socket in ruby, and for some reason my code keeps on blocking whilst calling recv
开发者_JS百科socket = TCPSocket.new("localhost",80)
socket.send r.join("\r\n"), 0
socket.flush
#We're only interested in the string "HTTP/1.1 XXX"
if http_status = get_http_status(socket.recv_nonblock(12))
if http_status == 200
$logger.info "Wrote #{message_packet}"
else
$logger.warn "Resubmitting message because #{line} is not 200"
@queue.publish(message)
end
end
#Get rid of the rest of the content
the_rest = socket.recv(1000)
while(the_rest != "") do
the_rest = socket.recv(1000)
end
From what I understand of recv
it should return nothing if there's no data waiting on the socket?
The connection could be a keep-alive connection. So, your recv() call wont end by itself. You will need to read the Content-Lenght header, then do a read of that many bytes from the content. After that you can get out of the RECV loop.
Or alternately, issue the request by setting "Connection: close" header so that the server closes the connection after sending the response.
精彩评论