2009-11-12 2 views
0

Ruby를 사용하여 간단한 UDP 클라이언트 및 서버를 설정하려고합니다. 코드는 다음과 같습니다Ruby UDP 서버/클라이언트 테스트가 실패했습니다.

require 'socket.so' 

class UDPClient 
    def initialize(host, port) 
    @host = host 
    @port = port 
    end 

    def start 
    @socket = UDPSocket.open 
    @socket.connect(@host, @port) 
    while true 
     @socket.send("otiro", 0, @host, @port) 
     sleep 2 
    end 
    end 
end 

client = UDPClient.new("10.10.129.139", 4321) # 10.10.129.139 is the IP of UDP server 
client.start 

지금, 나는 리눅스를 실행하는 두 버추얼 머신이 있습니다

require 'socket.so' 

class UDPServer 
    def initialize(port) 
    @port = port 
    end 

    def start 
    @socket = UDPSocket.new 
    @socket.bind(nil, @port) # is nil OK here? 
    while true 
     packet = @socket.recvfrom(1024) 
     puts packet 
    end 
    end 
end 

server = UDPServer.new(4321) 
server.start 

이것은 클라이언트입니다. 그들은 같은 네트워크에 있으며 서로 핑할 수 있습니다.

하지만 기계 A의 UDP 서버를 시작하고 기계 BI에 UDP 클라이언트를 실행하려고하면 다음 오류 얻을 :

client.rb:13:in `send': Connection refused - sendto(2) (Errno::ECONNREFUSED) 

나는 오류가에 바인드 방법에 의심을 섬기는 사람. 어떤 주소를 지정해야할지 모르겠습니다. 나는 당신이 LAN/WAN 인터페이스의 주소를 사용해야한다는 것을 읽었지 만 그 주소를 얻는 방법을 모르겠습니다.

아무도 도와 줄 수 있습니까?

답변

4

호스트 매개 변수 nil로컬 호스트으로 이해되므로 외부 시스템은 해당 소켓에 연결할 수 없습니다. 대신이 시도 : 워드 프로세서

@socket.bind('', @port) # '' ==> INADDR_ANY 

Socket을 위해 :

host is a host name or an address string (dotted decimal for IPv4, or a hex string for IPv6) for which to return information. A nil is also allowed, its meaning depends on flags, see below.

....

Socket::AI_PASSIVE: when set, if host is nil the ‘any’ address will be returned, Socket::INADDR_ANY or 0 for IPv4, "0::0" or "::" for IPv6. This address is suitable for use by servers that will bind their socket and do a passive listen, thus the name of the flag. Otherwise the local or loopback address will be returned, this is "127.0.0.1" for IPv4 and "::1’ for IPv6

+0

가 ''또는 바인드 방법 소켓 :: INADDR_ANY IP로 주소를 사용하여 문제를 해결합니다. 감사! – StackedCrooked

0

서버의 @socket.bind("10.10.129.139", @port)이 작동하지 않습니까?

편집 :

보통 당신이 하나의 시스템에 여러 개의 네트워크 인터페이스 (WLAN, LAN, ...)을 가질 수있다. 그들은 모두 서로 다른 IP 주소를 가지므로 하나 이상의 호스트 주소에 서버를 바인드해야합니다.

관련 문제