UDPSocket
UDPSocket (UDP/IP 소켓)
UDPSocket는 UDP/IP 소켓을 나타내는 클래스예요. TCP와 달리 연결을 맺지 않는(connectionless) 방식이라, 데이터그램 단위로 데이터를 주고받아요.
출처: Ruby 3.3 API
본문
new([address_family]) → socket
새 UDPSocket 객체를 만들어요. address_family는 정수, 문자열 또는 심볼이면 돼요. Socket::AF_INET, "AF_INET", :INET 등이 그 예시예요.
require 'socket'
UDPSocket.new #=> #<UDPSocket:fd 3>
UDPSocket.new(Socket::AF_INET6) #=> #<UDPSocket:fd 4>
bind(host, port) → 0
udpsocket를 host:port에 바인딩해요.
u1 = UDPSocket.new
u1.bind("127.0.0.1", 4913)
u1.send "message-to-self", 0, "127.0.0.1", 4913
p u1.recvfrom(10) #=> ["message-to", ["AF_INET", 4913, "localhost", "127.0.0.1"]]
connect(host, port) → 0
udpsocket를 host:port에 연결해요. 이렇게 하면 목적지 주소 없이도 send할 수 있게 돼요.
u1 = UDPSocket.new
u1.bind("127.0.0.1", 4913)
u2 = UDPSocket.new
u2.connect("127.0.0.1", 4913)
u2.send "uuuu", 0
p u1.recvfrom(10) #=> ["uuuu", ["AF_INET", 33230, "localhost", "127.0.0.1"]]
send(mesg, flags, host, port) → numbytes_sent
udpsocket를 통해 mesg를 전송해요. flags는 Socket::MSG_* 상수들의 비트 OR(bitwise OR)이어야 해요. 아래처럼 목적지 주소를 배열(sockaddr)로 주거나 아예 생략할 수도 있어요.
send(mesg, flags, sockaddr_to) → numbytes_sentsend(mesg, flags) → numbytes_sent
u1 = UDPSocket.new
u1.bind("127.0.0.1", 4913)
u2 = UDPSocket.new
u2.send "hi", 0, "127.0.0.1", 4913
mesg, addr = u1.recvfrom(10)
u1.send mesg, 0, addr[3], addr[1]
p u2.recv(100) #=> "hi"
recvfrom_nonblock(maxlen [, flags[, outbuf [, options]]]) → [mesg, sender_inet_addr]
기본 파일 디스크립터에 O_NONBLOCK이 설정된 뒤 recvfrom(2)를 사용해 udpsocket에서 최대 maxlen 바이트를 받아요. flags는 MSG_ 옵션 중 0개 이상이에요.
결과의 첫 요소 mesg는 받은 데이터, 두 번째 요소 sender_inet_addr은 발신자 주소를 나타내는 배열이에요. recvfrom(2)가 0을 반환하면 Socket#recv_nonblock은 nil을 돌려줘요. 대부분의 경우 연결이 닫혔다는 뜻이지만, 기반 API가 두 경우를 구분할 수 없어서 빈 패킷이 수신됐을 수도 있어요.
maxlen- 소켓에서 받을 바이트 수flags-MSG_옵션 중 0개 이상outbuf- 수신 데이터를 담을 목적지 String 버퍼options-exception: false를 지원하는 키워드 해시
require 'socket'
s1 = UDPSocket.new
s1.bind("127.0.0.1", ...)
# ...