Method: Socket#accept_nonblock
- Defined in:
- lib/socket.rb
#accept_nonblock(exception: true) ⇒ Object
call-seq:
socket.accept_nonblock([]) => [client_socket, client_addrinfo]
Accepts an incoming connection using accept(2) after O_NONBLOCK is set for the underlying file descriptor. It returns an array containing the accepted socket for the incoming connection, client_socket, and an Addrinfo, client_addrinfo.
Example
# In one script, 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)
begin # emulate blocking accept
client_socket, client_addrinfo = socket.accept_nonblock
rescue IO::WaitReadable, Errno::EINTR
IO.select([socket])
retry
end
puts "The client said, '#{client_socket.readline.chomp}'"
client_socket.puts "Hello from script one!"
socket.close
# In another script, 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 "Hello from script 2."
puts "The server said, '#{socket.readline.chomp}'"
socket.close
Refer to Socket#accept for the exceptions that may be thrown if the call to accept_nonblock fails.
Socket#accept_nonblock may raise any error corresponding to accept(2) failure, including Errno::EWOULDBLOCK.
If the exception is Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::ECONNABORTED or Errno::EPROTO, it is extended by IO::WaitReadable. So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock.
By specifying a keyword argument exception to false
, you can indicate that accept_nonblock should not raise an IO::WaitReadable exception, but return the symbol :wait_readable
instead.
See
-
Socket#accept
598 599 600 |
# File 'lib/socket.rb', line 598 def accept_nonblock(exception: true) __accept_nonblock(exception) end |