Class: Sip2::NonBlockingSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/sip2/non_blocking_socket.rb

Overview

Class Method Summary collapse

Class Method Details

.connect(host, port, timeout = 5) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/sip2/non_blocking_socket.rb', line 10

def self.connect(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
      # immediately it 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 # rubocop:disable Lint/HandleExceptions
          # 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 'Connection timeout'
      end
    end
  end
end