agent.lua 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. local skynet = require "skynet"
  2. local socket = require "skynet.socket"
  3. local sproto = require "sproto"
  4. local sprotoloader = require "sprotoloader"
  5. local WATCHDOG
  6. local host
  7. local send_request
  8. local CMD = {}
  9. local REQUEST = {}
  10. local client_fd
  11. function REQUEST:get()
  12. print("get", self.what)
  13. local r = skynet.call("SIMPLEDB", "lua", "get", self.what)
  14. return { result = r }
  15. end
  16. function REQUEST:set()
  17. print("set", self.what, self.value)
  18. local r = skynet.call("SIMPLEDB", "lua", "set", self.what, self.value)
  19. end
  20. function REQUEST:handshake()
  21. return { msg = "Welcome to skynet, I will send heartbeat every 5 sec." }
  22. end
  23. function REQUEST:quit()
  24. skynet.call(WATCHDOG, "lua", "close", client_fd)
  25. end
  26. local function request(name, args, response)
  27. local f = assert(REQUEST[name])
  28. local r = f(args)
  29. if response then
  30. return response(r)
  31. end
  32. end
  33. local function send_package(pack)
  34. local package = string.pack(">s2", pack)
  35. socket.write(client_fd, package)
  36. end
  37. skynet.register_protocol {
  38. name = "client",
  39. id = skynet.PTYPE_CLIENT,
  40. unpack = function (msg, sz)
  41. return host:dispatch(msg, sz)
  42. end,
  43. dispatch = function (fd, _, type, ...)
  44. assert(fd == client_fd) -- You can use fd to reply message
  45. skynet.ignoreret() -- session is fd, don't call skynet.ret
  46. skynet.trace()
  47. if type == "REQUEST" then
  48. local ok, result = pcall(request, ...)
  49. if ok then
  50. if result then
  51. send_package(result)
  52. end
  53. else
  54. skynet.error(result)
  55. end
  56. else
  57. assert(type == "RESPONSE")
  58. error "This example doesn't support request client"
  59. end
  60. end
  61. }
  62. function CMD.start(conf)
  63. local fd = conf.client
  64. local gate = conf.gate
  65. WATCHDOG = conf.watchdog
  66. -- slot 1,2 set at main.lua
  67. host = sprotoloader.load(1):host "package"
  68. send_request = host:attach(sprotoloader.load(2))
  69. skynet.fork(function()
  70. while true do
  71. send_package(send_request "heartbeat")
  72. skynet.sleep(500)
  73. end
  74. end)
  75. client_fd = fd
  76. skynet.call(gate, "lua", "forward", fd)
  77. end
  78. function CMD.disconnect()
  79. -- todo: do something before exit
  80. skynet.exit()
  81. end
  82. skynet.start(function()
  83. skynet.dispatch("lua", function(_,_, command, ...)
  84. skynet.trace()
  85. local f = CMD[command]
  86. skynet.ret(skynet.pack(f(...)))
  87. end)
  88. end)