Replacement in 1.9 for Socket's ready? method
For some time I have been using an old Ruby distribution (I think it was 1.8.6) on which I coded with the socket library. The old library had a method called ready?, which checked whether there was still data to be received without blocking. What would be the best replacement for that in 1.9?
The reason why I require it is as I have a program structured like this:
def handle_socket_messages
while true
break unless messages_to_send
sent_messages
end
while @s and @s.ready?
#read messages
readSt开发者_C百科r = @s.recv(0x1024)
...
end
end
(I then have another loop which keeps executing the handle_socket_messages method and then uses a sleep, so that the loop doesn't spin too fast, along with some other methods.
As you can see, I need to check whether I will receive data using @s.ready? (@s is a socket), otherwise the loops hang at readStr = @s.recv(0x1024), where the socket keeps wanting to receive data which the server doesn't send (It's waiting for data when it shouldn't).
What would be the best replacement for this method?
The solution was:
class Socket
def ready
not IO.select([self], nil, nil, 0) == nil
end
end
I've been using the ready?
method successfully in Ruby 2.2.2 by requiring io/wait
. There is a bit more info in this SO answer: https://stackoverflow.com/a/3983850/2464
精彩评论