2009-11-12 100 views
0

我想使用Ruby来设置一个简单的UDP客户端和服务器。代码如下所示:Ruby UDP服务器/客户端测试失败

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 

这是客户:

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 

现在,我已经运行Linux 2个VirtualBox虚拟机。他们在同一个网络中,他们可以互相ping通。

但是当我启动计算机A上的UDP服务器,然后尝试在机器BI运行UDP客户端收到以下错误:

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

我怀疑是错误是在上绑定方法服务器。我不知道我应该在那里指定哪个地址。我在某处读到应该使用LAN/WAN接口的地址,但我不知道如何获取该地址。

任何人都可以帮我这个吗?

回答

4

您的主机参数nil被理解为localhost,因此外部机器将无法连接到该套接字。试试这个:

@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 2009-11-12 14:45:19

0

@socket.bind("10.10.129.139", @port)在服务器不能正常工作?

编辑:

通常,你可以在一台机器上的多个网络接口(WLAN,LAN,..)。它们都具有不同的IP地址,因此您必须将服务器绑定到至少一个主机地址。