client.lua 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package.cpath = "luaclib/?.so"
  2. package.path = "lualib/?.lua;examples/?.lua"
  3. if _VERSION ~= "Lua 5.4" then
  4. error "Use lua 5.4"
  5. end
  6. local socket = require "client.socket"
  7. local proto = require "proto"
  8. local sproto = require "sproto"
  9. local host = sproto.new(proto.s2c):host "package"
  10. local request = host:attach(sproto.new(proto.c2s))
  11. local fd = assert(socket.connect("127.0.0.1", 8888))
  12. local function send_package(fd, pack)
  13. local package = string.pack(">s2", pack)
  14. socket.send(fd, package)
  15. end
  16. local function unpack_package(text)
  17. local size = #text
  18. if size < 2 then
  19. return nil, text
  20. end
  21. local s = text:byte(1) * 256 + text:byte(2)
  22. if size < s+2 then
  23. return nil, text
  24. end
  25. return text:sub(3,2+s), text:sub(3+s)
  26. end
  27. local function recv_package(last)
  28. local result
  29. result, last = unpack_package(last)
  30. if result then
  31. return result, last
  32. end
  33. local r = socket.recv(fd)
  34. if not r then
  35. return nil, last
  36. end
  37. if r == "" then
  38. error "Server closed"
  39. end
  40. return unpack_package(last .. r)
  41. end
  42. local session = 0
  43. local function send_request(name, args)
  44. session = session + 1
  45. local str = request(name, args, session)
  46. send_package(fd, str)
  47. print("Request:", session)
  48. end
  49. local last = ""
  50. local function print_request(name, args)
  51. print("REQUEST", name)
  52. if args then
  53. for k,v in pairs(args) do
  54. print(k,v)
  55. end
  56. end
  57. end
  58. local function print_response(session, args)
  59. print("RESPONSE", session)
  60. if args then
  61. for k,v in pairs(args) do
  62. print(k,v)
  63. end
  64. end
  65. end
  66. local function print_package(t, ...)
  67. if t == "REQUEST" then
  68. print_request(...)
  69. else
  70. assert(t == "RESPONSE")
  71. print_response(...)
  72. end
  73. end
  74. local function dispatch_package()
  75. while true do
  76. local v
  77. v, last = recv_package(last)
  78. if not v then
  79. break
  80. end
  81. print_package(host:dispatch(v))
  82. end
  83. end
  84. send_request("handshake")
  85. send_request("set", { what = "hello", value = "world" })
  86. while true do
  87. dispatch_package()
  88. local cmd = socket.readstdin()
  89. if cmd then
  90. if cmd == "quit" then
  91. send_request("quit")
  92. else
  93. send_request("get", { what = cmd })
  94. end
  95. else
  96. socket.usleep(100)
  97. end
  98. end