Module: CgminerApiClient::SocketWithTimeout

Included in:
Miner
Defined in:
lib/cgminer_api_client/socket_with_timeout.rb

Instance Method Summary collapse

Instance Method Details

#open_socket(host, port, timeout) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/cgminer_api_client/socket_with_timeout.rb', line 3

def open_socket(host, port, timeout)
  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
      socket.connect_nonblock(sockaddr)
    rescue IO::WaitWritable
      if IO.select(nil, [socket], nil, timeout)
        begin
          socket.connect_nonblock(sockaddr)
        rescue Errno::EISCONN
          # the socket is connected
        rescue
          socket.close
          raise
        end
      else
        socket.close
        raise "Connection timeout"
      end
    end
  end
end