一个 NodeMCU 中多个用户尝试连接时出现的问题

我正在使用 Lua 和 NodeMCU 板进行一个小项目,但我对这两个主题都很陌生,并且我遇到了一些麻烦。

我已经将一个按钮连接到了设备上,我想做的就是手动认证。当一个用户连接到 nodeMCU 上的服务器后,他将收到一个控制页面,在该页面上必须按下按钮,刷新页面并查看我在设备上加载的网页。

我现在遇到的问题是,当一个用户按下按钮后,每个新用户连接到服务器时都会完全跳过第一阶段,直接连接到网页。

我已经尝试了一些解决方案,但没有一个真正起作用。我正在考虑在一个用户按下按钮之后初始化一个字符串,该字符串可以作为某种会话令牌,但我不知道那是否真的有用。 有没有更简单的解决方案?

下面是我的代码:

auth.lua

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive", function(client,request)

    local buf = "";
    local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
    if(method == nil)then
        _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
    end
    local _GET = {}
    if (vars ~= nil)then
        for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
            _GET[k] = v
        end
    end
    buf=buf.."<html><body>"
    buf = buf.."<h1> 控制 Web 服务器</h1>";
    buf=buf.."<p> 按下设备上连接的按钮并在下面点击</p>"
    buf=buf.."<p><button onclick=\"history.go(0)\">前进</button></p>"
    buf = buf.."</form></body></html>"

    local _on,_off = "",""

    gpio.mode(1 ,gpio.INPUT,gpio.PULLUP)

    function debounce (func)
        local last = 0
        local delay = 200000

        return function (...)
            local now = tmr.now()
            if now - last < delay then return end

            last = now
            return func(...)
            end
    end

    function onChange()
        if gpio.read(1) == 0 then
    assert(loadfile("server.lua"))
            tmr.delay(500000)
            end
end

gpio.trig(1,"down", debounce(onChange))

    client:send(buf);
    client:close();
    collectgarbage();
    end)
end)

server.lua

srv:listen(80,function(conn)
conn:on("receive", function(client,payload)
       tgtfile = string.sub(payload,string.find(payload,"GET /")
       +5,string.find(payload,"HTTP/")-2)
    if tgtfile == "" then tgtfile = "index.htm" end

    local f = file.open(tgtfile,"r")
    if f ~= nil then
        client:send(file.read())
        file.close()
    else
        client:send("<html>"..tgtfile.." 未找到 - 404 错误<BR><a href='index.htm'/<%= @a %>> 主页</a><BR>")
    end
    client:close();
    collectgarbage();
    f = nil
    tgtfile = nil
end)
end)
点赞
用户1580216
用户1580216

我认为问题在于 onChange 函数所加载的 server.lua 中的 srv: listen() 也是在端口 80 上。auth.lua 中的 srv: listen() 不再被调用,因为它们都在端口 80 上,因此新的 listen() 将接管。

您需要以某种方式将您的代码全部放在同一个 srv:listen() 函数中,并将有关客户端的某些信息(例如其 IP、cookie 或其他信息)存储在数组中。

2017-01-10 22:31:15