gate.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. local skynet = require "skynet"
  2. local gateserver = require "snax.gateserver"
  3. local watchdog
  4. local connection = {} -- fd -> connection : { fd , client, agent , ip, mode }
  5. skynet.register_protocol {
  6. name = "client",
  7. id = skynet.PTYPE_CLIENT,
  8. }
  9. local handler = {}
  10. function handler.open(source, conf)
  11. watchdog = conf.watchdog or source
  12. return conf.address, conf.port
  13. end
  14. function handler.message(fd, msg, sz)
  15. -- recv a package, forward it
  16. local c = connection[fd]
  17. local agent = c.agent
  18. if agent then
  19. -- It's safe to redirect msg directly , gateserver framework will not free msg.
  20. skynet.redirect(agent, c.client, "client", fd, msg, sz)
  21. else
  22. skynet.send(watchdog, "lua", "socket", "data", fd, skynet.tostring(msg, sz))
  23. -- skynet.tostring will copy msg to a string, so we must free msg here.
  24. skynet.trash(msg,sz)
  25. end
  26. end
  27. function handler.connect(fd, addr)
  28. local c = {
  29. fd = fd,
  30. ip = addr,
  31. }
  32. connection[fd] = c
  33. skynet.send(watchdog, "lua", "socket", "open", fd, addr)
  34. end
  35. local function unforward(c)
  36. if c.agent then
  37. c.agent = nil
  38. c.client = nil
  39. end
  40. end
  41. local function close_fd(fd)
  42. local c = connection[fd]
  43. if c then
  44. unforward(c)
  45. connection[fd] = nil
  46. end
  47. end
  48. function handler.disconnect(fd)
  49. close_fd(fd)
  50. skynet.send(watchdog, "lua", "socket", "close", fd)
  51. end
  52. function handler.error(fd, msg)
  53. close_fd(fd)
  54. skynet.send(watchdog, "lua", "socket", "error", fd, msg)
  55. end
  56. function handler.warning(fd, size)
  57. skynet.send(watchdog, "lua", "socket", "warning", fd, size)
  58. end
  59. local CMD = {}
  60. function CMD.forward(source, fd, client, address)
  61. local c = assert(connection[fd])
  62. unforward(c)
  63. c.client = client or 0
  64. c.agent = address or source
  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)