0

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
        readStr = @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?

Speed
  • 1,424
  • 1
  • 16
  • 24
  • 1
    Maybe [`Kernel#select`](http://ruby-doc.org/core/classes/Kernel.html#M001406) which is just a wrapper for the [`select`](http://www.kernel.org/doc/man-pages/online/pages/man2/select.2.html) system call. An [SO search](http://stackoverflow.com/search?q=%5Bruby%5D+select+socket) should give you a quick overview. – mu is too short Jul 29 '11 at 07:55
  • Thanks, I was able to fix it: not IO.select([self], nil, nil, 0) == nil – Speed Jul 29 '11 at 08:33
  • The `IO.select` documentation is rather, um, sparse. No wonder you didn't know about it. – mu is too short Jul 29 '11 at 08:37
  • 1
    Yes I noticed it redirects to itself :S – Speed Jul 29 '11 at 21:20

2 Answers2

0

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

Community
  • 1
  • 1
slothbear
  • 2,016
  • 3
  • 21
  • 38
0

The solution was:

class Socket
    def ready
        not IO.select([self], nil, nil, 0) == nil
    end
end
Speed
  • 1,424
  • 1
  • 16
  • 24
  • Any idea what the tradeoffs are between calling `IO.select` and the `#ready?` method from the `io/wait` standard library? I've read the source for both with no enlightenment. – slothbear Sep 15 '15 at 00:18