webserver.lua 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. local skynet = require "skynet"
  2. local socket = require "skynet.socket"
  3. local logger = require "logger"
  4. local table_concat = table.concat
  5. local skynet_send = skynet.send
  6. local function ipaddr_parse(addr)
  7. -- check for format 1.11.111.111 for IPV4
  8. local chunks = {addr:match("(%d+)%.(%d+)%.(%d+)%.(%d+)")}
  9. if #chunks == 4 then
  10. return table_concat(chunks, ".")
  11. end
  12. -- check for IPV6 format, should be 8 'chunks' of numbers/letters
  13. -- without trailing chars
  14. local chunks = {addr:match(("([a-fA-F0-9]*):"):rep(8):gsub(":$","$"))}
  15. if #chunks == 8 then
  16. return table_concat(chunks, ":")
  17. end
  18. return addr
  19. end
  20. skynet.start(function()
  21. logger.label("<Webserver>")
  22. local agent = {}
  23. for index=1, 3 do
  24. table.insert(agent, skynet.newservice("webagent", index))
  25. end
  26. local balance = 1
  27. local webport = assert(option.web_port)
  28. local id = socket.listen(option.web_host, webport)
  29. logger.info(option.web_host ..":%d", webport)
  30. socket.start(id, function(fd, addr)
  31. local ipaddr = ipaddr_parse(addr)
  32. skynet_send(agent[balance], "lua", "dispatch", fd, ipaddr)
  33. balance = balance + 1
  34. if balance > #agent then
  35. balance = 1
  36. end
  37. end)
  38. end)