create a udp client on a specific port in ruby

Here's an example UDP client in Ruby that connects to a server on a specific port and sends a message:

main.rb
require 'socket'

server_port = 1234
server_host = 'localhost'

client = UDPSocket.new
client.connect(server_host, server_port)
client.send("Hello, server!", 0)
client.close
174 chars
10 lines

In this example, we create a new UDPSocket object and use the connect method to specify the server's host and port. Then we send a message using the send method, and finally close the socket with the close method.

Note that if you don't call connect before sending data, Ruby will choose a random port to send from. By calling connect, we ensure that our client sends data from a specific port.

related categories

gistlibby LogSnag