Method: Socket.tcp

Defined in:
lib/socket.rb

.tcp(host, port, local_host = nil, local_port = nil, connect_timeout: nil, resolv_timeout: nil) ⇒ Object

:call-seq:

Socket.tcp(host, port, local_host=nil, local_port=nil, [opts]) {|socket| ... }
Socket.tcp(host, port, local_host=nil, local_port=nil, [opts])

creates a new socket object connected to host:port using TCP/IP.

If local_host:local_port is given, the socket is bound to it.

The optional last argument opts is options represented by a hash. opts may have following options:

:connect_timeout

specify the timeout in seconds.

If a block is given, the block is called with the socket. The value of the block is returned. The socket is closed when this method returns.

If no block is given, the socket is returned.

Socket.tcp("www.ruby-lang.org", 80) {|sock|
  sock.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
  sock.close_write
  puts sock.read
}


628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/socket.rb', line 628

def self.tcp(host, port, local_host = nil, local_port = nil, connect_timeout: nil, resolv_timeout: nil) # :yield: socket
  last_error = nil
  ret = nil

  local_addr_list = nil
  if local_host != nil || local_port != nil
    local_addr_list = Addrinfo.getaddrinfo(local_host, local_port, nil, :STREAM, nil)
  end

  Addrinfo.foreach(host, port, nil, :STREAM, timeout: resolv_timeout) {|ai|
    if local_addr_list
      local_addr = local_addr_list.find {|local_ai| local_ai.afamily == ai.afamily }
      next unless local_addr
    else
      local_addr = nil
    end
    begin
      sock = local_addr ?
        ai.connect_from(local_addr, timeout: connect_timeout) :
        ai.connect(timeout: connect_timeout)
    rescue SystemCallError
      last_error = $!
      next
    end
    ret = sock
    break
  }
  unless ret
    if last_error
      raise last_error
    else
      raise SocketError, "no appropriate local address"
    end
  end
  if block_given?
    begin
      yield ret
    ensure
      ret.close
    end
  else
    ret
  end
end