Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

BasicSocket#recv_nonblock

(::Integer maxlen, ?::Integer flags, ?::String buf, ?exception: ::boolish) -> (::String | :wait_readable)
basicsocket.recv_nonblock(maxlen [, flags [, buf [, options ]]]) => mesg

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 the MSG_ options

  • buf - destination String buffer

  • options - keyword hash, supporting ‘exception: false`

Example

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.

See

See also #recvmsg_nonblock #remote_address #recvmsg #send also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0