开发者

Ruby UDP server/client test fails

开发者 https://www.devze.com 2022-12-11 19:31 出处:网络
I am trying to setup a simple UDP client and server using Ruby. The code looks like this: require \'socket.so\'

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 thi开发者_JAVA技巧s one?


Your host parameter nil is understood as localhost, so an external machine won't be able to connect to that socket. Try this instead:

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

From the docs for 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消