gate.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. local skynet = require "skynet"
  2. local gateserver = require "snax.gateserver"
  3. local netpack = require "skynet.netpack"
  4. local watchdog
  5. local connection = {} -- fd -> connection : { fd , client, agent , ip, mode }
  6. local forwarding = {} -- agent -> connection
  7. skynet.register_protocol {
  8. name = "client",
  9. id = skynet.PTYPE_CLIENT,
  10. }
  11. local handler = {}
  12. function handler.open(source, conf)
  13. watchdog = conf.watchdog or source
  14. end
  15. function handler.message(fd, msg, sz)
  16. -- recv a package, forward it
  17. local c = connection[fd]
  18. local agent = c.agent
  19. if agent then
  20. skynet.redirect(agent, c.client, "client", fd, msg, sz)
  21. else
  22. skynet.send(watchdog, "lua", "socket", "data", fd, netpack.tostring(msg, sz))
  23. end
  24. end
  25. function handler.connect(fd, addr)
  26. local c = {
  27. fd = fd,
  28. ip = addr,
  29. }
  30. connection[fd] = c
  31. skynet.send(watchdog, "lua", "socket", "open", fd, addr)
  32. end
  33. local function unforward(c)
  34. if c.agent then
  35. forwarding[c.agent] = nil
  36. c.agent = nil
  37. c.client = nil
  38. end
  39. end
  40. local function close_fd(fd)
  41. local c = connection[fd]
  42. if c then
  43. unforward(c)
  44. connection[fd] = nil
  45. end
  46. end
  47. function handler.disconnect(fd)
  48. close_fd(fd)
  49. skynet.send(watchdog, "lua", "socket", "close", fd)
  50. end
  51. function handler.error(fd, msg)
  52. close_fd(fd)
  53. skynet.send(watchdog, "lua", "socket", "error", fd, msg)
  54. end
  55. function handler.warning(fd, size)
  56. skynet.send(watchdog, "lua", "socket", "warning", fd, size)
  57. end
  58. local CMD = {}
  59. function CMD.forward(source, fd, client, address)
  60. local c = assert(connection[fd])
  61. unforward(c)
  62. c.client = client or 0
  63. c.agent = address or source
  64. forwarding[c.agent] = c
  65. gateserver.openclient(fd)
  66. end
  67. function CMD.accept(source, fd)
  68. local c = assert(connection[fd])
  69. unforward(c)
  70. gateserver.openclient(fd)
  71. end
  72. function CMD.kick(source, fd)
  73. gateserver.closeclient(fd)
  74. end
  75. function handler.command(cmd, source, ...)
  76. local f = assert(CMD[cmd])
  77. return f(source, ...)
  78. end
  79. gateserver.start(handler)