The io/wait standard library may be useful here. As a result, it creates streaming I / O operations (sockets and tubes), some of which, for example, ready? . According to the documentation , ready? returns non-nil if there are free bytes without blocking. It so happens that the non-nil value returns the number of bytes available in the MRI.
Here is an example that creates a dumb small socket server and then connects to it with the client. The server simply sends "foo" and then closes the connection. The client waits a bit to give the server time to send, and then prints how many bytes are available for reading. An interesting material for you is located at the client:
require 'socket' require 'io/wait'
Do not use this server code in anything real. He deliberately lingers to a simple example.
Note. According to Pickax, io / wait is only available if the FIONREAD function is in ioctl (2). "What is it on Linux. I donβt know about Windows and others.
source share