02.11.2017, 07:50
Use this as a starting point, it uses non-blocking socket.select() so UDP won't interfere. The only blocking part is TCP re-connection. There's no need to close/open local UDP server each time.
Code:
if not sockets then
require('socket')
clientip = '192.168.1.xx'
clientport = 9090
serverport = 12007
udpserver = socket.udp()
udpserver:setsockname('127.0.0.1', serverport)
udpserver:settimeout(0)
sockets = { udpserver }
function tcpconnect()
local tcpclient = socket.tcp()
tcpclient:settimeout(1)
if tcpclient:connect(clientip, clientport) then
tcpclient:settimeout(0)
else
tcpclient:close()
tcpclient = nil
os.sleep(1)
end
return tcpclient
end
function reconnect()
repeat
tcpclient = tcpconnect()
until tcpclient
sockets[ 2 ] = tcpclient
end
function errhandler()
tcpclient:close()
reconnect()
end
function clienthandler()
while true do
local char, err = tcpclient:receive(1)
if char then
...
else
if err == 'closed' then
errhandler()
end
break
end
end
end
function serverhandler()
local msg = udpserver:receive()
if tcpclient then
tcpclient:send(msg)
end
end
reconnect()
end
res = socket.select(sockets, nil, 1)
if res then
if res[ tcpclient ] then
clienthandler()
end
if res[ udpserver ] then
serverhandler()
end
end