forked from devyte/nodemcu-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpserver.lua
47 lines (38 loc) · 1.29 KB
/
tcpserver.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
return function (port, _servermodules)
assert((not not wifi.sta.getip()) or (not not wifi.ap.getip()), "tcpserver: No viable IP found")
assert(_servermodules ~= nil, "tcpserver: no server modules specified")
local servermodules = _servermodules
local function detector(conn, payload)
local serverOnReceive = dofile("tcpserver-detector.lc")(servermodules, payload, conn)
collectgarbage()
if not serverOnReceive then
--no server matched, so close
print("tcpserver: unknown protocol")
conn:close()
return
end
--forward payload to server onReceive
serverOnReceive(conn, payload)
end
local s = net.createServer(net.TCP, 180) -- 180 seconds client timeout
s:listen(port, function(conn)
conn:on("receive", detector)
end)
print("tcpserver running on port ".. port)
local tcpserver = {}
function tcpserver:close()
servermodules = nil
s:close()
s = nil
collectgarbage()
end
function tcpserver:getModules()
return servermodules
end
function tcpserver:setModule(m, e)
if servermodules[m] ~= nil then
servermodules[m] = e
end
end
return tcpserver
end