再升级websocket模块

This commit is contained in:
MrZ626
2021-07-23 23:11:07 +08:00
parent 6aa8de3506
commit 84b5790ab2
3 changed files with 25 additions and 22 deletions

View File

@@ -15,7 +15,7 @@ do--Connect
SOCK:settimeout(timeout)
local res,err=SOCK:connect(host,port)
if err then CHN_push(readCHN,err)return end
assert(res,err)
--WebSocket handshake
if not body then body=''end
@@ -33,7 +33,7 @@ do--Connect
--First line of HTTP
res,err=SOCK:receive('*l')
if not res then CHN_push(readCHN,err)return end
assert(res,err)
local code,ctLen
code=res:find(' ')
code=res:sub(code+1,code+3)
@@ -41,7 +41,7 @@ do--Connect
--Get body length from headers and remove headers
repeat
res,err=SOCK:receive('*l')
if not res then CHN_push(readCHN,err)return end
assert(res,err)
if not ctLen and res:find('length')then
ctLen=tonumber(res:match('%d+'))
end
@@ -53,13 +53,8 @@ do--Connect
CHN_push(readCHN,'success')
else
res,err=SOCK:receive(ctLen)
if not res then
CHN_push(readCHN,err)
else
res=JSON.decode(res)
CHN_push(readCHN,(code or"XXX")..":"..(res and res.reason or"Server Error"))
end
return
res=JSON.decode(assert(res,err))
error((code or"XXX")..":"..(res and res.reason or"Server Error"))
end
end
end
@@ -102,7 +97,6 @@ local sendThread=coroutine.wrap(function()
end
YIELD()
end
error("break")
end)
local function _receive(sock,len)
@@ -131,7 +125,7 @@ local readThread=coroutine.wrap(function()
while true do
--Byte 0-1
res,err=_receive(SOCK,2)
assert(not err,err)
assert(res,err)
op=band(byte(res,1),0x0f)
fin=band(byte(res,1),0x80)==0x80
@@ -140,17 +134,17 @@ local readThread=coroutine.wrap(function()
local length=band(byte(res,2),0x7f)
if length==126 then
res,err=_receive(SOCK,2)
assert(not err,err)
assert(res,err)
length=shl(byte(res,1),8)+byte(res,2)
elseif length==127 then
local lenData
lenData,err=_receive(SOCK,8)
assert(not err,err)
assert(res,err)
local _,_,_,_,_5,_6,_7,_8=byte(lenData,1,8)
length=shl(_5,24)+shl(_6,16)+shl(_7,8)+_8
end
res,err=_receive(SOCK,length)
assert(not err,err)
assert(res,err)
--React
if op==8 then--8=close
@@ -178,7 +172,6 @@ local readThread=coroutine.wrap(function()
end
YIELD()
end
error("break")
end)
local success,err
@@ -193,4 +186,5 @@ end
SOCK:close()
CHN_push(readCHN,8)--close
CHN_push(readCHN,err or"Disconnected")
CHN_push(readCHN,err or"Disconnected")
error()