#!/usr/bin/ruby require "socket" $KCODE='u' @port=10000 # default port number @port=ARGV[0] || 10000 COMMAND_CODE_ZIP_TO_ADDR = 0x01 COMMAND_CODE_ZIP_TO_ADDR_RESPONSE = 0x02 COMMAND_CODE_ADDR_TO_ZIP = 0x11 COMMAND_CODE_ADDR_TO_ZIP_RESPONSE = 0x12 def resp(code, ver, converted, zip, addr, sock) addr = (addr ? addr.tr("\0", "") : "") len = 1 + 7 + addr.size + 1 len_h = len / 256 len_l = len % 256 msg = " " * len msg[0] = code msg[1] = ver msg[2] = len_h msg[3] = len_l msg[4] = converted msg[5..11] = zip ? zip : "0000000" msg[12..-1] = addr + "\0" sock.write(msg) end def zip_to_addr_ver1(zip, sock) zip_to_addr_map = { "1000004" => "東京都千代田区大手町", } addr = zip_to_addr_map[zip] #puts "#{zip} => #{addr}" resp COMMAND_CODE_ZIP_TO_ADDR_RESPONSE, 1, addr ? 1 : 0, zip, addr, sock end def addr_to_zip_ver1(addr, sock) addr_to_zip_map = { "東京都千代田区大手町" => "1000004", } zip = addr_to_zip_map[addr.tr("\0", "")] #puts "#{addr} => #{zip}" resp COMMAND_CODE_ADDR_TO_ZIP_RESPONSE, 1, zip ? 1 : 0, zip, addr, sock end fntbl = { [ COMMAND_CODE_ZIP_TO_ADDR, 1 ] => method(:zip_to_addr_ver1), [ COMMAND_CODE_ADDR_TO_ZIP, 1 ] => method(:addr_to_zip_ver1), } begin server_sock = TCPServer.open(@port) loop do Thread.start(server_sock.accept) do |s| begin head = s.read(4) code = head[0] ver = head[1] len_h = head[2] len_l = head[3] len = (len_h << 8) + len_l body = s.read(len) fntbl[[code, ver]].call(body, s) rescue puts $!.to_s puts $!.backtrace ensure s.close end end end rescue ensure server_sock.close if server_sock != nil end