diff --git a/ruby-sockets/line-protocol/client.rb b/ruby-sockets/line-protocol/client.rb new file mode 100644 index 0000000..b384121 --- /dev/null +++ b/ruby-sockets/line-protocol/client.rb @@ -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 diff --git a/ruby-sockets/line-protocol/server.rb b/ruby-sockets/line-protocol/server.rb new file mode 100644 index 0000000..6a52f9f --- /dev/null +++ b/ruby-sockets/line-protocol/server.rb @@ -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