Ruby TCPSocket recv blocking and never returning
So, I have the following code:
def LSCPHandler.send_message(message, hostname, port)
s = TCPSocket.open(hostname, port)
s.print message
ret = s.recv(1024)
s.close
LSCPHandler.parse_error(ret)
return ret
end
Which works just fine, normally. The server I'm talking to returns the response pretty quickly, usually, and all is well.
Then, today, something went wrong with the server. Not my problem, BUT, this resulted in my entire application hanging, waiting for recv to time out. This isn't exactly optimal.
Is there a way to time out recv if I dont' hear something back immediately? I tried looking at the ruby documentation, but it really confuses me(i.e. TCPSocket only implements three methods, none of them open or recv, and it's parent class of Socket doesn't i开发者_运维百科mplemente these methods either. And Socket's parent class appears to be Object? I'm throughly confused)
You can set the receive timeout socket options on the socket to something else than the default. The tricky bit is to pick a suitable number that still works in all use cases, i.e. you don't want your recv
call to timeout too early.
s.setsockopt(Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, <timeout>)
精彩评论