create a udp server on a specific port in ruby

Here's an example code snippet for creating a UDP server on a specific port in Ruby:

main.rb
require 'socket'

port = 9999 #choose any available port
server = UDPSocket.new
server.bind(nil, port)

loop do
  message, sender = server.recvfrom(1000) # receive messages up to 1000 bytes
  puts "Received message: #{message} from #{sender}"
  server.send("ACK: #{message}", 0, sender[3], sender[1]) # send acknowledgement to client
end
338 chars
12 lines

In this example, we create a new UDPSocket object, bind it to the specified port, and then enter an infinite loop where we receive messages and send acknowledgements back to the client. The recvfrom method accepts a maximum number of bytes to receive, and returns the message itself as well as information about the sender. The send method is used to send an acknowledgement message back to the same sender.

gistlibby LogSnag