Skip to content

Commit

Permalink
remove verbose comments, add link to author
Browse files Browse the repository at this point in the history
  • Loading branch information
szymonsobczak committed Dec 30, 2014
1 parent b06ce97 commit 08c85fb
Showing 1 changed file with 1 addition and 12 deletions.
13 changes: 1 addition & 12 deletions lib/poseidon/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,37 +109,26 @@ def ensure_connected
end
end

# Explained on http://spin.atomicobject.com/2013/09/30/socket-connection-timeout-ruby/
def connect_with_timeout(host, port, timeout = 5)
# Convert the passed host into structures the non-blocking calls can deal with
addr = Socket.getaddrinfo(host, nil)
sockaddr = Socket.pack_sockaddr_in(port, addr[0][3])

Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0).tap do |socket|
socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)

begin
# Initiate the socket connection in the background. If it doesn't fail
# immediatelyit will raise an IO::WaitWritable (Errno::EINPROGRESS)
# indicating the connection is in progress.
socket.connect_nonblock(sockaddr)

rescue IO::WaitWritable
# IO.select will block until the socket is writable or the timeout
# is exceeded - whichever comes first.
if IO.select(nil, [socket], nil, timeout)
begin
# Verify there is now a good connection
socket.connect_nonblock(sockaddr)
rescue Errno::EISCONN
# Good news everybody, the socket is connected!
rescue
# An unexpected exception was raised - the connection is no good.
socket.close
raise
end
else
# IO.select returns nil when the socket is not ready before timeout
# seconds have elapsed
socket.close
raise TimeoutException
end
Expand Down

0 comments on commit 08c85fb

Please sign in to comment.