我想使用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接口的地址,但我不知道如何获取该地址。
任何人都可以帮我这个吗?
使用 '' 或插槽:: INADDR_ANY作为IP地址绑定的方法解决了这个问题。谢谢! – StackedCrooked 2009-11-12 14:45:19