Last active
November 19, 2019 06:16
-
-
Save pgdaniel/daa525240422b22f2426e848d9ea9084 to your computer and use it in GitHub Desktop.
TCP binary protocol server/client (inspired/borrowed from https://gist.github.com/omnisis/3998752)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bindata' | |
class CustomProtocol < BinData::Record | |
endian :big | |
stringz :command_word | |
uint32 :op1 | |
uint32 :op2 | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require_relative 'protocol' | |
$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 = sock.gets | |
puts "server responded: #{msg} " | |
end | |
def send_request(sock, data) | |
sock.puts(data) | |
end | |
1000.times do |i| | |
puts i | |
s = TCPSocket.new($host, $port) | |
req1 = make_request("ADD",i ,i) | |
puts "sending add request over socket ..." | |
send_request(s, req1.to_binary_s) | |
print_answer(s) | |
s.close | |
s = TCPSocket.new($host, $port) | |
req2 = make_request("MULT",i, i) | |
puts "sending multiply request over socket ..." | |
send_request(s, req2.to_binary_s) | |
print_answer(s) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require_relative 'protocol' # needed for custom binary protocol | |
port = 9999 | |
puts "Started TCP server on #{port}..." | |
Socket.tcp_server_loop(port) { |msg| | |
proto = CustomProtocol.new | |
proto.read(msg) | |
#puts proto.command_word | |
if proto.command_word == "ADD" | |
#puts "Received ADD command" | |
result = (proto.op1 + proto.op2) | |
#puts result | |
msg.puts(result.to_s) | |
elsif proto.command_word == "MULT" | |
#puts "Received MULTIPLY command" | |
result = (proto.op1 * proto.op2) | |
msg.puts(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