20.04.2022, 06:31
Code:
function read(sock)
local buf = {}
while true do
local ch, err = sock:receive(1)
if ch then
local pr = buf[ #buf ]
buf[ #buf + 1 ] = ch
if ch == '#' and pr == '#' then
break
end
else
return nil, err
end
end
local ret = table.concat(buf)
log(ret)
return ret
end
ACK = '*#*1##'
NACK = '*#*0##'
OPEN = '*99*1##'
function openwebnetinit()
local socket = require('socket')
local sock = socket.tcp()
sock:settimeout(1)
local res, err = socket.connect('192.168.1.247', 20000)
if not res then
alert('connect failed ' .. tostring(err))
return
end
res, err = read(sock)
if res ~= ACK then
alert('no initial ack ' .. tostring(res or err))
return
end
sock:send(OPEN)
res, err = read(sock)
if not res then
alert('no nonce ' .. tostring(err))
return
end
local nonce = res:match('%d+')
res, err = read(sock)
if res ~= ACK then
alert('auth failed ' .. tostring(res or err))
return
end
return sock
end
sock = openwebnetinit()
if sock then
alert('connection ok')
-- do something here
sock:close()
end
Code:
Resident script:5: calling 'receive' on bad self (tcp{client} expected, got userdata)
stack traceback:
[C]: in function 'receive'
Resident script:5: in function 'read'
Resident script:43: in function 'openwebnetinit'