Skip to content

Instantly share code, notes, and snippets.

@pgdaniel
Forked from omnisis/protocol.rb
Created November 19, 2019 05:55
Show Gist options
  • Save pgdaniel/aea29d996c8fb015ef78ada7b8044880 to your computer and use it in GitHub Desktop.
Save pgdaniel/aea29d996c8fb015ef78ada7b8044880 to your computer and use it in GitHub Desktop.
Ruby UDP Server/Client Pair with Custom Binary Protocol
require 'bindata'
class CustomProtocol < BinData::Record
endian :big
stringz :command_word
uint8 :op1
uint8 :op2
end
require 'socket'
require_relative 'protocol'
# Connection params
$port = 9999
$host = 'localhost'
def make_request(cmd, a,b)
add_request = CustomProtocol.new
add_request.command_word = cmd
add_request.op1 = a
add_request.op2 = b
add_request
end
def print_answer(sock)
msg, sender = sock.recvfrom(20) # reads up to 20 bytes
puts "server responded: #{msg} "
end
def send_request(sock, data)
sock.send(data, 0, $host, $port)
end
# -- MAIN --
# open the connection
s = UDPSocket.new
# make an add request and send it out over the socket
# print the answer by reading the result off the socket
req1 = make_request("ADD",5,4)
puts "sending add request over socket ..."
send_request(s, req1.to_binary_s)
print_answer(s)
# ok, now try a multiply request
req2 = make_request("MULT",6,7)
puts "sending multiply request over socket ..."
send_request(s, req2.to_binary_s)
print_answer(s)
require 'socket' # needed for Socket library
require_relative 'protocol' # needed for custom binary protocol
port = 9999
puts "Started UDP server on #{port}..."
Socket.udp_server_loop(port) { |msg, msg_src|
proto = CustomProtocol.new
proto.read(msg)
if proto.command_word == "ADD"
puts "Received ADD command"
result = proto.op1 + proto.op2
msg_src.reply result.to_s
elsif proto.command_word == "MULT"
puts "Received MULTIPLY command"
result = proto.op1 * proto.op2
msg_src.reply result.to_s
else
puts "Received uknown cmd msg: #{proto.command_word} ..."
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment