Ruby TCPSocket: find out how much data is available

Is there a way to find out how many data bytes are available on a TCPSocket in Ruby? That is, how many bytes can be ready without locking?

+4
source share
1 answer

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' # Server server_socket = TCPServer.new('localhost', 0) port = server_socket.addr[1] Thread.new do session = server_socket.accept sleep 0.5 session.puts "foo" session.close end # Client client_socket = TCPSocket.new('localhost', port) puts client_socket.ready? # => nil sleep 1 puts client_socket.ready? # => 4 

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.

+5
source

All Articles