websocket.lua 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. --- 模块功能:websocket客户端
  2. -- @module websocket
  3. -- @author OpenLuat
  4. -- @license MIT
  5. -- @copyright OpenLuat.com
  6. -- @release 2021.04.08
  7. require "utils"
  8. require "socket"
  9. module(..., package.seeall)
  10. local magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
  11. local ws = {}
  12. ws.__index = ws
  13. local function websocket(url, cert)
  14. return setmetatable({
  15. io = nil,
  16. url = url,
  17. key = "",
  18. wss = "",
  19. cert = cert,
  20. host = "",
  21. port = "",
  22. input = "",
  23. callbacks = {},
  24. send_data = {},
  25. send_text = nil,
  26. sendsize = 1460,
  27. open_callback = false,
  28. connected = false,
  29. terminated = false,
  30. readyState = "CONNECTING",
  31. }, ws)
  32. end
  33. --- 创建 websocket 对象
  34. -- @string url,websocket服务器的连接地址,格式为ws(或wss)://xxx 开头
  35. -- @table[opt=nil] cert,ssl连接需要的证书配置,cert格式如下:
  36. -- {
  37. -- caCert = "ca.crt", --CA证书文件(Base64编码 X.509格式),如果存在此参数,则表示客户端会对服务器的证书进行校验;不存在则不校验
  38. -- clientCert = "client.crt", --客户端证书文件(Base64编码 X.509格式),服务器对客户端的证书进行校验时会用到此参数
  39. -- clientKey = "client.key", --客户端私钥文件(Base64编码 X.509格式)
  40. -- clientPassword = "123456", --客户端证书文件密码[可选]
  41. -- insist = 1, --证书中的域名校验失败时,是否坚持连接,默认为1,坚持连接,0为不连接
  42. -- }
  43. -- @return table:返回1个websocket对象
  44. -- @usage local ws = websocket.new("ws://121.40.165.18:8800")
  45. function new(url, cert)
  46. return websocket(url, cert)
  47. end
  48. --- ws:on 注册函数
  49. -- @string event,事件,可选值"open","message","close","error","pong"
  50. -- @function callback,回调方法,message|error|pong 形参是该方法需要的数据。
  51. -- @usage mt:on("message",function(message) local print(message)end)
  52. function ws:on(event, callback)
  53. self.callbacks[event] = callback
  54. end
  55. --- websocket 与 websocket 服务器建立连接
  56. -- @number timeout,与 websocket 服务器建立连接最长超时
  57. -- @return bool,true,表示连接成功,false or nil 表示连接失败
  58. -- @usage while not ws:connect(20000) do sys.wait(2000) end
  59. function ws:connect(timeout)
  60. self.wss, self.host, self.port, self.path = self.url:match("(%a+)://([%w%.%-]+):?(%d*)(.*)")
  61. self.wss, self.host = self.wss:lower(), self.host:lower()
  62. self.port = self.port ~= "" and self.port or (self.wss == "wss" and 443 or 80)
  63. if self.wss == "wss" then
  64. self.io = socket.tcp(true,self.cert)
  65. else
  66. self.io = socket.tcp()
  67. end
  68. if not self.io then
  69. log.error("websocket:connect:", "没有可用的TCP通道!")
  70. return false
  71. end
  72. log.info("websocket url:", self.url)
  73. if not self.io:connect(self.host, self.port, timeout) then
  74. log.error("websocket:connect", "服务器连接失败!")
  75. return false
  76. end
  77. self.key = crypto.base64_encode(math.random(100000000000000,999999999999999) .. 0, 16)
  78. local req = "GET " .. self.path .. " HTTP/1.1\r\nHost: " .. self.host .. ":" .. self.port ..
  79. "\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n" .. "Origin: http://" .. self.host ..
  80. "\r\nSec-WebSocket-Version: 13\r\n" .. "Sec-WebSocket-Key: " .. self.key .. "\r\n\r\n"
  81. if self.io:send(req, tonumber(timeout) or 20000) then
  82. local r, s = self.io:recv(tonumber(timeout) or 5000)
  83. if not r then
  84. self.io:close()
  85. log.error("websocket:connect", "与 websocket server 握手超时!")
  86. return false
  87. end
  88. local _, idx, code = s:find("%s(%d+)%s.-\r\n")
  89. if code == "101" then
  90. local header, accept = {}, self.key .. magic
  91. accept = crypto.sha1(accept, #accept):fromHex()
  92. accept = crypto.base64_encode(accept, #accept)
  93. for k, v in string.gmatch(s:sub(idx + 1, -1), "(.-):%s*(.-)\r\n") do header[k:lower()] = v end
  94. if header["sec-websocket-accept"] and header["sec-websocket-accept"] == accept then
  95. log.info("websocket:connect", "与 websocket server 握手成功!")
  96. self.connected, self.readyState = true, "OPEN"
  97. if self.callbacks.open then self.open_callback = true end
  98. return true
  99. end
  100. end
  101. end
  102. log.error("websocket:connect", "与 websocket server 握手失败!")
  103. return false
  104. end
  105. -- 掩码加密
  106. -- mask: 4位长度掩码字符串
  107. -- data: 待加密的字符串
  108. -- return: 掩码加密后的字符串
  109. local function wsmask(mask, data)
  110. local i = 0
  111. return data:gsub(".", function(c)
  112. i = i + 1
  113. return string.char(bit.bxor(data:byte(i), mask:byte((i - 1) % 4 + 1)))
  114. end)
  115. end
  116. --- websocket发送帧方法
  117. -- @bool fin, true 表示结束帧,false表示延续帧
  118. -- @number opcode, 0x0 -- 0xF,其他值非法,代码意义参考websocket手册
  119. -- @string data, 用户要发送的数据
  120. -- @usage self:sendFrame(true, 0x1, "www.openluat.com")
  121. function ws:sendFrame(fin, opcode, data)
  122. if not self.connected then return end
  123. local finbit, maskbit, len = fin and 0x80 or 0, 0x80, #data
  124. local frame = pack.pack("b", bit.bor(finbit, opcode))
  125. if len < 126 then
  126. frame = frame .. pack.pack("b", bit.bor(len, maskbit))
  127. elseif len < 0xFFFF then
  128. frame = frame .. pack.pack(">bH", bit.bor(126, maskbit), len)
  129. else
  130. -- frame = frame .. pack.pack(">BL", bit.bor(127, maskbit), len)
  131. log.error("ws:sendFrame", "数据长度超过最大值!")
  132. end
  133. local mask = pack.pack(">I", os.time())
  134. frame = frame .. mask .. wsmask(mask, data)
  135. for i = 1, #frame, self.sendsize do
  136. if not self.io:send(frame:sub(i, i + self.sendsize - 1)) then break end
  137. end
  138. end
  139. -- websocket 发送用户数据方法
  140. -- @string data: 用户要发送的字符串数据
  141. -- @bool text: true 数据为文本字符串,nil或false数据为二进制数据。
  142. -- @usage self:send("www.openluat.com")
  143. -- @usage self:send("www.openluat.com",true)
  144. -- @usage self:send(string.fromHex("www.openluat.com"))
  145. local function send(ws,data, text)
  146. if text then
  147. log.info("websocket cleint send:", data:sub(1, 100))
  148. ws:sendFrame(true, 0x1, data)
  149. else
  150. ws:sendFrame(true, 0x2, data)
  151. end
  152. if ws.callbacks.sent then ws.callbacks.sent() end
  153. end
  154. function ws:send(data, text)
  155. table.insert(self.send_data, data)
  156. self.send_text = text
  157. sys.publish("WEBSOCKET_SEND_DATA","send")
  158. end
  159. -- websocket发送ping包
  160. -- @string data: 用户要发送的文本数据
  161. -- @usage self:ping("hello")
  162. local function ping(ws,data)
  163. ws:sendFrame(true, 0x9, data)
  164. end
  165. function ws:ping(data)
  166. table.insert(self.send_data, data)
  167. sys.publish("WEBSOCKET_SEND_DATA","ping")
  168. end
  169. -- websocket发送文本数据方法
  170. -- @string data: 用户要发送的文本数据
  171. -- @usage self:pone("hello")
  172. local function pong(ws,data)
  173. ws:sendFrame(true, 0xA, data)
  174. end
  175. function ws:pong(data)
  176. self:sendFrame(true, 0xA, data)
  177. end
  178. -- 处理 websocket 发过来的数据并解析帧数据
  179. -- @return string : 返回解析后的单帧用户数据
  180. function ws:recvFrame()
  181. local close_ctrl="EXIT_TASK"..self.io.id
  182. local r, s , p = self.io:recv(60000,"WEBSOCKET_SEND_DATA")
  183. if not r then
  184. if s=="timeout" then
  185. return false, nil, "WEBSOCKET_OK"
  186. elseif s=="WEBSOCKET_SEND_DATA" then
  187. if p=="send" then
  188. local send_data = table.concat(self.send_data)
  189. local send_text = self.send_text
  190. self.send_data = {}
  191. self.send_text = nil
  192. send(self,send_data, send_text)
  193. elseif p=="ping" then
  194. local send_data = table.concat(self.send_data)
  195. self.send_data = {}
  196. ping(self,send_data)
  197. elseif p=="pong" then
  198. local send_data = table.concat(self.send_data)
  199. self.send_data = {}
  200. pong(self,send_data)
  201. elseif p == close_ctrl then
  202. return false, nil, close_ctrl
  203. end
  204. return false, nil, "WEBSOCKET_OK"
  205. else
  206. return false, nil, "Read byte error!"
  207. end
  208. end
  209. local _, firstByte, secondByte = pack.unpack(s:sub(1,2), "bb")
  210. local fin = bit.band(firstByte, 0x80) ~= 0
  211. local rsv = bit.band(firstByte, 0x70) ~= 0
  212. local opcode = bit.band(firstByte, 0x0f)
  213. local isControl = bit.band(opcode, 0x08) ~= 0
  214. -- 检查RSV1,RSV2,RSV3 是否为0,客户端不支持扩展
  215. if rsv then return false, nil, "服务器正在使用未定义的扩展!" end
  216. -- 检查数据是否存在掩码加密
  217. local maskbit = bit.band(secondByte, 0x80) ~= 0
  218. local length = bit.band(secondByte, 0x7f)
  219. if isControl and (length >= 126 or not fin) then
  220. return false, nil, "控制帧异常!"
  221. end
  222. if maskbit then
  223. return false, nil, "数据帧被掩码处理过!"
  224. end
  225. -- 获取载荷长度
  226. if length == 126 then
  227. -- if not r then return false, nil, "读取帧载荷长度失败!" end
  228. _, length = pack.unpack(s:sub(3,4), ">H")
  229. elseif length == 127 then
  230. return false, nil, "数据帧长度超过支持范围!"
  231. end
  232. -- 获取有效载荷数据
  233. if length > 0 then
  234. if length>126 then
  235. -- r, s = self.io:recv()
  236. s=s:sub(5,5+length-1)
  237. else
  238. s=s:sub(3,3+length-1)
  239. end
  240. -- if not r then return false, nil, "读取帧有效载荷数据失败!" end
  241. end
  242. -- 处理切片帧
  243. if not fin then -- 切片未完成
  244. return true, false, s
  245. else -- 未分片帧
  246. if opcode < 0x3 then -- 数据帧
  247. return true, true, s
  248. elseif opcode == 0x8 then -- close
  249. local code, reason
  250. if #s >= 2 then
  251. _, code = pack.unpack(s:sub(1, 2), ">H")
  252. end
  253. if #s > 2 then
  254. reason = s:sub(3)
  255. end
  256. self.terminated = true
  257. -- self:close(code, reason)
  258. return false, nil, reason
  259. elseif opcode == 0x9 then --Ping
  260. self:pong(s)
  261. elseif opcode == 0xA then -- Pong
  262. if self.callbacks.pong then self.callbacks.pong(s) end
  263. end
  264. return true, true, nil
  265. end
  266. end
  267. --- 处理 websocket 发过来的数据并拼包
  268. -- @return result, boolean: 返回数据的状态 true 为正常, false 为失败
  269. -- @return data, string: result为true时为数据,false时为报错信息
  270. -- @usage local result, data = ws:recv()
  271. function ws:recv()
  272. local data = ""
  273. while true do
  274. local success, final, message = self:recvFrame()
  275. -- 数据帧解析错误
  276. if not success then
  277. return success, message
  278. end
  279. -- 数据帧分片处理
  280. if message then
  281. data = data .. message
  282. else
  283. data = "" --数据帧包含控制帧处理
  284. end
  285. -- 数据帧处理完成
  286. if final and message then
  287. break
  288. end
  289. end
  290. if self.callbacks.message then self.callbacks.message(data) end
  291. return true, data
  292. end
  293. --- 关闭 websocket 与服务器的链接
  294. -- @number code,1000 或 1002 等,请参考websocket标准
  295. -- @string reason,关闭原因
  296. -- @return nil
  297. -- @usage ws:close()
  298. -- @usage ws:close(1002,"协议错误")
  299. function ws:close(code, reason)
  300. -- 1000 "normal closure" status code
  301. self.readyState = "CLOSING"
  302. if self.terminated then
  303. log.error("ws:close server code:", code, reason)
  304. elseif self.io.connected then
  305. if code == nil and reason ~= nil then
  306. code = 1000
  307. end
  308. local data = ""
  309. if code ~= nil then
  310. data = pack.pack(">H", code)
  311. end
  312. if reason ~= nil then
  313. data = data .. reason
  314. end
  315. self.terminated = true
  316. self:sendFrame(true, 0x8, data)
  317. end
  318. self.io:close()
  319. self.readyState, self.connected = "CLOSED", false
  320. if self.callbacks.close then self.callbacks.close(code or 1001) end
  321. self.input = ""
  322. end
  323. --- 主动退出一个指定的websocket任务
  324. -- @传入一个websocket对象
  325. -- @return nil
  326. -- @usage wesocket.exit(ws)
  327. function exit(ws)
  328. sys.publish("WEBSOCKET_SEND_DATA", "EXIT_TASK"..ws.io.id)
  329. end
  330. --- 获取websocket当前状态
  331. -- @return string,状态值("CONNECTING","OPEN","CLOSING","CLOSED")
  332. -- @usage ws:state()
  333. function ws:state()
  334. return self.readyState
  335. end
  336. --- 获取websocket与服务器连接状态
  337. -- @return boolean: true 连接成功,其他值连接失败
  338. -- @usage ws:online()
  339. function ws:online()
  340. return self.connected
  341. end
  342. --- websocket 需要在任务中启动,带自动重连,支持心跳协议
  343. -- @number[opt=nil] keepAlive,websocket心跳包,建议180秒
  344. -- @function[opt=nil] proc,处理服务器下发消息的函数
  345. -- @number[opt=1000] reconnTime,断开链接后的重连时间
  346. -- @return nil
  347. -- @usage sys.taskInit(ws.start,ws,180)
  348. -- @usage sys.taskInit(ws.start,ws,180,function(msg)u1:send(msg) end)
  349. function ws:start(keepAlive, proc, reconnTime)
  350. reconnTime = tonumber(reconnTime) and reconnTime * 1000 or 1000
  351. if tonumber(keepAlive) then
  352. keepAlivetimer=sys.timerLoopStart(self.ping, keepAlive * 1000, self, "heart")
  353. end
  354. while true do
  355. while not socket.isReady() do sys.wait(1000) end
  356. if self:connect() then
  357. local close_ctrl="EXIT_TASK"..self.io.id
  358. repeat
  359. local r, message = self:recv()
  360. if self.open_callback == true then self.callbacks.open() self.open_callback = false end
  361. if r then
  362. if type(proc) == "function" then proc(message) end
  363. elseif message == close_ctrl then
  364. self:close()
  365. sys.timerStop(keepAlivetimer)
  366. if self.io.id ~= nil then
  367. self=nil
  368. end
  369. return true
  370. elseif not r and message ~="WEBSOCKET_OK" then
  371. log.error('ws recv error', message)
  372. end
  373. until not r and message ~="WEBSOCKET_OK"
  374. end
  375. self:close()
  376. log.info("websocket:Start", "与 websocket Server 的连接已断开!")
  377. sys.wait(reconnTime)
  378. end
  379. end