ws.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. local request = require("fastweb.request")
  2. local response = require("fastweb.response")
  3. local ws = require("fastweb.websocket")
  4. local codec = require("fastweb.codec")
  5. local base64 = require("base64")
  6. local utils = require("utils")
  7. if not ws.valid() then
  8. response.response_done()
  9. return
  10. end
  11. if ws.type() == ws.UPGRADE then
  12. print("[WS_UPGRADE] CONNID:" .. ws.connid())
  13. local accept_key = base64.encode(utils.hex_to_bytes(codec.sha1(ws.sec_websocket_key() .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")))
  14. response.header("Sec-WebSocket-Accept", accept_key)
  15. response.header("Connection", "Upgrade")
  16. response.header("Upgrade", "websocket")
  17. response.send_header(101, "Switching Protocols")
  18. elseif ws.type() == ws.MESSAGE_HEADER then
  19. local opcode = ws.opcode()
  20. local log = "[WS_HEADER] CONNID:" .. ws.connid()
  21. if opcode == ws.OPCODE_TEXT then
  22. log = log .. " [TEXT]"
  23. elseif opcode == ws.OPCODE_BINARY then
  24. log = log .. " [BINARY]"
  25. elseif opcode == ws.OPCODE_CLOSE then
  26. log = log .. " [CLOSE]"
  27. elseif opcode == ws.OPCODE_PING then
  28. log = log .. " [PING]"
  29. elseif opcode == ws.OPCODE_PONG then
  30. log = log .. " [PONG]"
  31. else
  32. log = log .. " [OPCODE:" .. opcode .. "]"
  33. end
  34. log = log .. " [FINAL:" .. tostring(ws.final()) .. "] [LENGTH:" .. ws.length() .. "]"
  35. print(log)
  36. elseif ws.type() == ws.MESSAGE_BODY then
  37. local connid = ws.connid()
  38. local opcode = ws.opcode()
  39. local body = request.body()
  40. local log = "[WS_BODY] CONNID:" .. connid
  41. .. " [OPCODE:" .. tostring(opcode) .. "]"
  42. .. " [LENGTH:" .. tostring(#body) .. "]"
  43. print(log)
  44. if opcode == ws.OPCODE_CLOSE then
  45. -- 客户端关闭:回 Close 帧(可带回原载荷),完成握手
  46. print("[WS_BODY] reply CLOSE")
  47. response.send_ws(body, ws.OPCODE_CLOSE)
  48. elseif opcode == ws.OPCODE_PING then
  49. -- Ping 必须回 Pong,载荷原样带回
  50. print("[WS_BODY] reply PONG")
  51. response.send_ws(body, ws.OPCODE_PONG)
  52. elseif opcode == ws.OPCODE_PONG then
  53. -- Pong 无需回复
  54. print("[WS_BODY] PONG ignored")
  55. elseif opcode == ws.OPCODE_TEXT or opcode == ws.OPCODE_BINARY then
  56. -- 文本/二进制:原样回显
  57. response.send_ws(body, opcode)
  58. else
  59. print("[WS_BODY] unhandled opcode:" .. tostring(opcode))
  60. end
  61. elseif ws.type() == ws.CLOSE then
  62. -- TCP 已断开,只做清理,不要再发帧
  63. print("[WS_CLOSE] CONNID:" .. ws.connid())
  64. return
  65. else
  66. print("UNKNOWN")
  67. end
  68. response.response_done()