Skip to content

Instantly share code, notes, and snippets.

@jwhiteman
Last active January 7, 2017 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwhiteman/510a64fe8a127b7a78cb6b62bb8bf37c to your computer and use it in GitHub Desktop.
Save jwhiteman/510a64fe8a127b7a78cb6b62bb8bf37c to your computer and use it in GitHub Desktop.
UDP in Ruby - packing socket manually
# or `echo some-request | nc localhost 8181 -4u `
MAX_READ = 1024 * 8
FLAGS = 0
c = Socket.new :INET, :DGRAM
s = Socket.pack_sockaddr_in 8181, "127.0.0.1"
c.send("some-request", FLAGS, s)
res = c.recv(MAX_READ)
MAX_READ = 1024 * 8
FLAGS = 0
trap(:INT) { exit }
s = Socket.new :INET, :DGRAM
a = Socket.pack_sockaddr_in 8181, "127.0.0.1"
s.bind(a)
loop do
req, addr = s.recvfrom(MAX_READ)
puts "server: #{req} from #{addr.inspect}"
s.send("some-response", FLAGS, addr)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment