TCPSocket

TCPSocket (TCP/IP 클라이언트 소켓)

TCPSocketTCP/IP 클라이언트 소켓을 나타내는 클래스예요. 서버에 연결해 데이터를 주고받을 때 사용해요.

출처: Ruby 3.3 API

본문

간단한 클라이언트는 이렇게 생겼어요.

require 'socket'

s = TCPSocket.new 'localhost', 2000

while line = s.gets # Read lines from socket
  puts line         # and print them
end

s.close             # close socket when done

new(remote_host, remote_port, local_host=nil, local_port=nil, connect_timeout: nil)

remote_hostremote_port로 TCP 연결을 열어요. local_hostlocal_port를 지정하면 그 값들을 로컬 쪽에서 연결을 만드는 데 사용해요. :connect_timeout은 초 단위의 타임아웃을 지정해요.

gethostbyname(hostname) → [official_hostname, alias_hostnames, address_family, *address_list]

Addrinfo.getaddrinfo를 대신 사용하세요. 이 메서드는 다음과 같은 이유로 더 이상 사용하지 않는(deprecated) 메서드예요.

  • 결과의 3번째 요소는 첫 번째 주소의 주소 패밀리(address family)인데, 나머지 주소들의 주소 패밀리는 반환되지 않아요.
  • gethostbyname()은 오래 걸리고 다른 스레드를 블로킹할 수 있어요. (gethostbyname()이 시스템 수준이라 GVL이 풀리지 않아요.)
  • 이 메서드는 시스템의 hosts 파일을 건너뛰어요.
  • IPv6에는 잘 맞지 않아요.

new(host, serv, *rest) 형태의 대체 생성자 호출 형태도 존재해요.