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 的 VirtualBox 机器。他们在同一个网络中,可以互相ping通。
但是当我在机器 A 上启动 UDP 服务器,然后尝试在机器 BI 上运行 UDP 客户端时,出现以下错误:
client.rb:13:in `send': Connection refused - sendto(2) (Errno::ECONNREFUSED)
我怀疑错误出在服务器上的绑定方法中。我不知道应该在那里指定哪个地址。我在某处读到您应该使用 LAN/WAN 接口的地址,但我不知道如何获取该地址。
谁能帮我解决这个问题吗?
I am trying to setup a simple UDP client and server using Ruby. The code looks like this:
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
This is the client:
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
Now, I have two VirtualBox machines running Linux. They are in the same network, they can ping to each other.
But when I start the UDP server on machine A, and then try to run the UDP client on machine B I get the following error:
client.rb:13:in `send': Connection refused - sendto(2) (Errno::ECONNREFUSED)
I suspect that the error is in the bind method on the server. I don't know which address I should specify there. I read somewhere that you should use the address of your LAN/WAN interface, but I don't how to obtain that address.
Can anyone help me with this one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的主机参数
nil
被理解为localhost,因此外部机器将无法连接到该套接字。试试这个:来自 Socket 的文档:
Your host parameter
nil
is understood as localhost, so an external machine won't be able to connect to that socket. Try this instead:From the docs for Socket:
服务器中的
@socket.bind("10.10.129.139", @port)
不起作用吗?编辑:
通常一台机器上可以有多个网络接口(WLAN、LAN,..)。它们都有不同的 IP 地址,因此您必须将一台服务器至少绑定到一个主机地址。
Is
@socket.bind("10.10.129.139", @port)
in the server not working?Edit:
Usually you could have multiple network interfaces on one machine (WLAN, LAN, ..). They all have different IP addresses, so you have to bind a server to at least one host address.