watchdog.lua 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. local skynet = require "skynet"
  2. local CMD = {}
  3. local SOCKET = {}
  4. local gate
  5. local agent = {}
  6. function SOCKET.open(fd, addr)
  7. skynet.error("New client from : " .. addr)
  8. agent[fd] = skynet.newservice("agent")
  9. skynet.call(agent[fd], "lua", "start", { gate = gate, client = fd, watchdog = skynet.self() })
  10. end
  11. local function close_agent(fd)
  12. local a = agent[fd]
  13. agent[fd] = nil
  14. if a then
  15. skynet.call(gate, "lua", "kick", fd)
  16. -- disconnect never return
  17. skynet.send(a, "lua", "disconnect")
  18. end
  19. end
  20. function SOCKET.close(fd)
  21. print("socket close",fd)
  22. close_agent(fd)
  23. end
  24. function SOCKET.error(fd, msg)
  25. print("socket error",fd, msg)
  26. close_agent(fd)
  27. end
  28. function SOCKET.warning(fd, size)
  29. -- size K bytes havn't send out in fd
  30. print("socket warning", fd, size)
  31. end
  32. function SOCKET.data(fd, msg)
  33. end
  34. function CMD.start(conf)
  35. return skynet.call(gate, "lua", "open" , conf)
  36. end
  37. function CMD.close(fd)
  38. close_agent(fd)
  39. end
  40. skynet.start(function()
  41. skynet.dispatch("lua", function(session, source, cmd, subcmd, ...)
  42. if cmd == "socket" then
  43. local f = SOCKET[subcmd]
  44. f(...)
  45. -- socket api don't need return
  46. else
  47. local f = assert(CMD[cmd])
  48. skynet.ret(skynet.pack(f(subcmd, ...)))
  49. end
  50. end)
  51. gate = skynet.newservice("gate")
  52. end)