Files
fastweb/www/api/ws.lua
2026-08-04 20:07:32 +08:00

78 lines
2.5 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
local request = require("fastweb.request")
local response = require("fastweb.response")
local ws = require("fastweb.websocket")
local codec = require("fastweb.codec")
local base64 = require("base64")
local utils = require("utils")
if not ws.valid() then
response.response_done()
return
end
if ws.type() == ws.UPGRADE then
print("[WS_UPGRADE] CONNID:" .. ws.connid())
local accept_key = base64.encode(utils.hex_to_bytes(codec.sha1(ws.sec_websocket_key() .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")))
response.header("Sec-WebSocket-Accept", accept_key)
response.header("Connection", "Upgrade")
response.header("Upgrade", "websocket")
response.send_header(101, "Switching Protocols")
elseif ws.type() == ws.MESSAGE_HEADER then
local opcode = ws.opcode()
local log = "[WS_HEADER] CONNID:" .. ws.connid()
if opcode == ws.OPCODE_TEXT then
log = log .. " [TEXT]"
elseif opcode == ws.OPCODE_BINARY then
log = log .. " [BINARY]"
elseif opcode == ws.OPCODE_CLOSE then
log = log .. " [CLOSE]"
elseif opcode == ws.OPCODE_PING then
log = log .. " [PING]"
elseif opcode == ws.OPCODE_PONG then
log = log .. " [PONG]"
else
log = log .. " [OPCODE:" .. opcode .. "]"
end
log = log .. " [FINAL:" .. tostring(ws.final()) .. "] [LENGTH:" .. ws.length() .. "]"
print(log)
elseif ws.type() == ws.MESSAGE_BODY then
local connid = ws.connid()
local opcode = ws.opcode()
local body = request.body()
local log = "[WS_BODY] CONNID:" .. connid
.. " [OPCODE:" .. tostring(opcode) .. "]"
.. " [LENGTH:" .. tostring(#body) .. "]"
print(log)
if opcode == ws.OPCODE_CLOSE then
-- 客户端关闭:回 Close 帧(可带回原载荷),完成握手
print("[WS_BODY] reply CLOSE")
response.send_ws(body, ws.OPCODE_CLOSE)
elseif opcode == ws.OPCODE_PING then
-- Ping 必须回 Pong载荷原样带回
print("[WS_BODY] reply PONG")
response.send_ws(body, ws.OPCODE_PONG)
elseif opcode == ws.OPCODE_PONG then
-- Pong 无需回复
print("[WS_BODY] PONG ignored")
elseif opcode == ws.OPCODE_TEXT or opcode == ws.OPCODE_BINARY then
-- 文本/二进制:原样回显
response.send_ws(body, opcode)
else
print("[WS_BODY] unhandled opcode:" .. tostring(opcode))
end
elseif ws.type() == ws.CLOSE then
-- TCP 已断开,只做清理,不要再发帧
print("[WS_CLOSE] CONNID:" .. ws.connid())
return
else
print("UNKNOWN")
end
response.response_done()