Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
BasicSocket#recv_nonblock
# File tmp/rubies/ruby-3.4.1/ext/socket/lib/socket.rb, line 376
def recv_nonblock(len, flag = 0, str = nil, exception: true)
__recv_nonblock(len, flag, str, exception)
end
Receives up to maxlen bytes from socket using recvfrom(2) after O_NONBLOCK is set for the underlying file descriptor. flags is zero or more of the MSG_ options. The result, mesg, is the data received.
When recvfrom(2) returns 0, Socket#recv_nonblock returns nil. In most cases it means the connection was closed, but for UDP connections it may mean an empty packet was received, as the underlying API makes it impossible to distinguish these two cases.
Parameters
-
maxlen- the number of bytes to receive from the socket -
flags- zero or more of theMSG_options -
buf- destinationStringbuffer -
options- keyword hash, supporting ‘exception: false`
Example
serv = TCPServer.new("127.0.0.1", 0) af, port, host, addr = serv.addr c = TCPSocket.new(addr, port) s = serv.accept c.send "aaa", 0 begin # emulate blocking recv. p s.recv_nonblock(10) #=> "aaa" rescue IO::WaitReadable IO.select([s]) retry end
Refer to Socket#recvfrom for the exceptions that may be thrown if the call to recv_nonblock fails.
BasicSocket#recv_nonblock may raise any error corresponding to recvfrom(2) failure, including Errno::EWOULDBLOCK.
If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN, it is extended by IO::WaitReadable. So IO::WaitReadable can be used to rescue the exceptions for retrying recv_nonblock.
By specifying a keyword argument exception to false, you can indicate that recv_nonblock should not raise an IO::WaitReadable exception, but return the symbol :wait_readable instead.