Class: Aerospike::Socket::TCP

Inherits:
Socket
  • Object
show all
Includes:
Base
Defined in:
lib/aerospike/socket/tcp.rb

Class Method Summary collapse

Methods included from Base

#alive?, #close, #connected?, #initialize, #read, #read_from_socket, #timeout=, #write, #write_to_socket

Class Method Details

.connect(host, port, timeout) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/aerospike/socket/tcp.rb', line 27

def self.connect(host, port, timeout)
  Aerospike.logger.debug("Trying to connect to #{host}:#{port} with #{timeout}s timeout")

  domain = if host.match(Resolv::IPv6::Regex)
    ::Socket::AF_INET6
  else
    ::Socket::AF_INET
  end

  sock = new(domain, ::Socket::SOCK_STREAM, 0)
  sockaddr = ::Socket.sockaddr_in(port, host)

  begin
    sock.connect_nonblock(sockaddr)
  rescue IO::WaitWritable, Errno::EINPROGRESS
    ::IO.select(nil, [sock], nil, timeout)

    # Because IO.select behaves (return values are different) differently on
    # different rubies, lets just try `connect_noblock` again. An exception
    # is raised to indicate the current state of the connection, and at this
    # point, we are ready to decide if this is a success or a timeout.
    begin
      sock.connect_nonblock(sockaddr)
    rescue Errno::EISCONN
      # Good, we're connected.
    rescue Errno::EINPROGRESS, Errno::EALREADY
      # Bad, we're still waiting to connect.
      raise ::Aerospike::Exceptions::Connection, "Connection attempt to #{host}:#{port} timed out after #{timeout} secs"
    rescue => e
      raise ::Aerospike::Exceptions::Connection, e.message
    end
  end

  sock
end