connect_nonblock(addr, exception: true) public

Requests a connection to be made on the given remote_sockaddr after O_NONBLOCK is set for the underlying file descriptor. Returns 0 if successful, otherwise an exception is raised.


# +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object


# Pull down Google's web page
require 'socket'
include Socket::Constants
socket =, SOCK_STREAM, 0)
sockaddr = Socket.sockaddr_in(80, '')
begin # emulate blocking connect
rescue IO::WaitWritable, [socket]) # wait 3-way handshake completion
    socket.connect_nonblock(sockaddr) # check connection failure
  rescue Errno::EISCONN
socket.write("GET / HTTP/1.0\r\n\r\n")
results =

Refer to Socket#connect for the exceptions that may be thrown if the call to connect_nonblock fails.

Socket#connect_nonblock may raise any error corresponding to connect(2) failure, including Errno::EINPROGRESS.

If the exception is Errno::EINPROGRESS, it is extended by IO::WaitWritable. So IO::WaitWritable can be used to rescue the exceptions for retrying connect_nonblock.

By specifying a keyword argument exception to false, you can indicate that connect_nonblock should not raise an IO::WaitWritable exception, but return the symbol :wait_writable instead.


# Socket#connect
Show source
Register or log in to add new notes.