laromicas
laromicas

Reputation: 46

Can I receive data using multiple UDP Ports in Ruby?

Is there a way I can listen to more than one port on UDPServer in Ruby? I need to listen to some devices that send me data over multiple ports, and I need to receive them and use the same operations on the data.

I'm right now using:

udp_socket = UDPSocket.new
udp_socket.bind( "", 8500 )

while($running) do
    payload, host = udp_socket.recvfrom(1500)
    process payload
end

but the code stops on:

payload, host = udp_socket.recvfrom(1500)

and I cannot run more code until it receives data.

Upvotes: 0

Views: 447

Answers (1)

davogones
davogones

Reputation: 7399

You could launch multiple threads.

require 'thread'

ports = [1500, 1501, 1502]

# Create threads to listen to each port
threads = ports.map do |port|
  Thread.new do
    while($running) do
      payload, host = udp_socket.recvfrom(port)
      process payload
    end
  end
end

# Wait for all threads to complete
threads.map &:join

Upvotes: 1

Related Questions