Playing around with line-based socket protocols
This commit is contained in:
parent
3b7d21b12f
commit
18808b88c3
37
ruby-sockets/line-protocol/client.rb
Normal file
37
ruby-sockets/line-protocol/client.rb
Normal file
@ -0,0 +1,37 @@
|
||||
require 'date'
|
||||
require 'time'
|
||||
require 'socket'
|
||||
|
||||
DATEFMT = '%Y%m%d%H%M%S'
|
||||
|
||||
def recordify(msg)
|
||||
code = '%-31s' % 'DERP'
|
||||
num = '%-12d' % (rand.to_s.tr('.', '0')[0,5]).to_i
|
||||
timestamp = Time.now.strftime(DATEFMT)
|
||||
len = '%-6d' % msg.length
|
||||
"#{code}#{num}#{len}#{timestamp}#{msg.gsub(/\r/, '\r').gsub(/\n/, '\n')}\r\n"
|
||||
end
|
||||
|
||||
def main
|
||||
print "What to say?: "
|
||||
msg = gets
|
||||
TCPSocket.open('127.0.0.1', 15778) do |sock|
|
||||
sock.send(recordify(msg), 0)
|
||||
response = sock.recv(66)
|
||||
sock.close
|
||||
|
||||
puts "raw response --> #{response.inspect}"
|
||||
code = response[0..30].to_s.strip
|
||||
num = response[31..42].to_s.strip
|
||||
raw_timestamp = response[49..62].to_s.strip
|
||||
timestamp = DateTime.strptime(raw_timestamp, DATEFMT)
|
||||
|
||||
puts "code: '#{code}'"
|
||||
puts "num: '#{num}'"
|
||||
puts "timestamp: '#{timestamp}'"
|
||||
end
|
||||
end
|
||||
|
||||
if __FILE__ == $0
|
||||
main
|
||||
end
|
45
ruby-sockets/line-protocol/server.rb
Normal file
45
ruby-sockets/line-protocol/server.rb
Normal file
@ -0,0 +1,45 @@
|
||||
require 'date'
|
||||
require 'time'
|
||||
require 'eventmachine'
|
||||
|
||||
DATEFMT = '%Y%m%d%H%M%S'
|
||||
|
||||
def generic_response
|
||||
code = '%-31s' % 'SNARF'
|
||||
num = '%-12d' % (rand.to_s.tr('.', '0')[0,5]).to_i
|
||||
filler = (' ' * 7)
|
||||
timestamp = Time.now.strftime(DATEFMT)
|
||||
"#{code}#{num}#{filler}#{timestamp}\r\n"
|
||||
end
|
||||
|
||||
module LineProtocolServer
|
||||
def post_init
|
||||
puts "# BEGIN CONN #{Time.now}"
|
||||
end
|
||||
|
||||
def receive_data(request)
|
||||
code = request[0..30].to_s.strip
|
||||
num = request[31..42].to_s.strip
|
||||
len = request[43..48].to_s.strip
|
||||
puts "raw date --> '#{request[49..62]}'"
|
||||
timestamp = DateTime.strptime(request[49..62].strip, DATEFMT)
|
||||
msg = request[63..(63 + len.to_i)].strip
|
||||
|
||||
puts "code: '#{code}'"
|
||||
puts "num: '#{num}'"
|
||||
puts "len: '#{len}'"
|
||||
puts "timestamp: '#{timestamp}'"
|
||||
puts "msg: '#{msg}'"
|
||||
|
||||
send_data(generic_response)
|
||||
end
|
||||
|
||||
def unbind
|
||||
puts "# END CONN #{Time.now}"
|
||||
end
|
||||
end
|
||||
|
||||
EventMachine.run do
|
||||
EventMachine.start_server('0.0.0.0', 15778, LineProtocolServer)
|
||||
puts 'Listening on 0.0.0.0:15778'
|
||||
end
|
Loading…
Reference in New Issue
Block a user