ws_Server.lua 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. local skynet = require "skynet"
  2. local socket = require "skynet.socket"
  3. local service = require "skynet.service"
  4. local websocket = require "http.websocket"
  5. local handle = {}
  6. local MODE = ...
  7. if MODE == "agent" then
  8. function handle.connect(id)
  9. print("ws connect from: " .. tostring(id))
  10. end
  11. function handle.handshake(id, header, url)
  12. local addr = websocket.addrinfo(id)
  13. print("ws handshake from: " .. tostring(id), "url", url, "addr:", addr)
  14. print("----header-----")
  15. for k,v in pairs(header) do
  16. print(k,v)
  17. end
  18. print("--------------")
  19. end
  20. function handle.message(id, msg, msg_type)
  21. assert(msg_type == "binary" or msg_type == "text")
  22. websocket.write(id, msg)
  23. end
  24. function handle.ping(id)
  25. print("ws ping from: " .. tostring(id) .. "\n")
  26. end
  27. function handle.pong(id)
  28. print("ws pong from: " .. tostring(id))
  29. end
  30. function handle.close(id, code, reason)
  31. print("ws close from: " .. tostring(id), code, reason)
  32. end
  33. function handle.error(id)
  34. print("ws error from: " .. tostring(id))
  35. end
  36. skynet.start(function ()
  37. skynet.dispatch("lua", function (_,_, id, protocol, addr)
  38. local ok, err = websocket.accept(id, handle, protocol, addr)
  39. if not ok then
  40. print(err)
  41. end
  42. end)
  43. end)
  44. else
  45. skynet.start(function ()
  46. local agent = {}
  47. for i= 1, 20 do
  48. agent[i] = skynet.newservice(SERVICE_NAME, "agent")
  49. end
  50. local balance = 1
  51. local protocol = "ws"
  52. local id = socket.listen("0.0.0.0", 8003)
  53. skynet.error(string.format("Listen websocket port 9948 protocol:%s", protocol))
  54. socket.start(id, function(id, addr)
  55. print(string.format("accept client socket_id: %s addr:%s", id, addr))
  56. skynet.send(agent[balance], "lua", id, protocol, addr)
  57. balance = balance + 1
  58. if balance > #agent then
  59. balance = 1
  60. end
  61. end)
  62. end)
  63. end