Method: Socket#recvfrom_nonblock
- Defined in:
- lib/socket.rb
#recvfrom_nonblock(len, flag = 0, str = nil, exception: true) ⇒ Object
call-seq:
socket.recvfrom_nonblock(maxlen[, flags[, outbuf[, opts]]]) => [mesg, sender_addrinfo]
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 first element of the results, mesg, is the data received. The second element, sender_addrinfo, contains protocol-specific address information of the sender.
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 maximum number of bytes to receive from the socket -
flags
- zero or more of theMSG_
options -
outbuf
- destination String buffer -
opts
- keyword hash, supporting ‘exception: false`
Example
# In one file, start this first
require 'socket'
include Socket::Constants
socket = Socket.new(AF_INET, SOCK_STREAM, 0)
sockaddr = Socket.sockaddr_in(2200, 'localhost')
socket.bind(sockaddr)
socket.listen(5)
client, client_addrinfo = socket.accept
begin # emulate blocking recvfrom
pair = client.recvfrom_nonblock(20)
rescue IO::WaitReadable
IO.select([client])
retry
end
data = pair[0].chomp
puts "I only received 20 bytes '#{data}'"
sleep 1
socket.close
# In another file, start this second
require 'socket'
include Socket::Constants
socket = Socket.new(AF_INET, SOCK_STREAM, 0)
sockaddr = Socket.sockaddr_in(2200, 'localhost')
socket.connect(sockaddr)
socket.puts "Watch this get cut short!"
socket.close
Refer to Socket#recvfrom for the exceptions that may be thrown if the call to recvfrom_nonblock fails.
Socket#recvfrom_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 recvfrom_nonblock.
By specifying a keyword argument exception to false
, you can indicate that recvfrom_nonblock should not raise an IO::WaitReadable exception, but return the symbol :wait_readable
instead.
See
-
Socket#recvfrom
541 542 543 |
# File 'lib/socket.rb', line 541 def recvfrom_nonblock(len, flag = 0, str = nil, exception: true) __recvfrom_nonblock(len, flag, str, exception) end |