simplemonitor.lua 838 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. local skynet = require "skynet"
  2. -- It's a simple service exit monitor, you can do something more when a service exit.
  3. local service_map = {}
  4. skynet.register_protocol {
  5. name = "client",
  6. id = skynet.PTYPE_CLIENT, -- PTYPE_CLIENT = 3
  7. unpack = function() end,
  8. dispatch = function(_, address)
  9. local w = service_map[address]
  10. if w then
  11. for watcher in pairs(w) do
  12. skynet.redirect(watcher, address, "error", 0, "")
  13. end
  14. service_map[address] = false
  15. end
  16. end
  17. }
  18. local function monitor(session, watcher, command, service)
  19. assert(command, "WATCH")
  20. local w = service_map[service]
  21. if not w then
  22. if w == false then
  23. skynet.ret(skynet.pack(false))
  24. return
  25. end
  26. w = {}
  27. service_map[service] = w
  28. end
  29. w[watcher] = true
  30. skynet.ret(skynet.pack(true))
  31. end
  32. skynet.start(function()
  33. skynet.dispatch("lua", monitor)
  34. end)