【问题标题】:Issue when more than one user tries to connect to my NodeMCU当多个用户尝试连接到我的 NodeMCU 时出现问题
【发布时间】:2017-05-24 21:08:11
【问题描述】:

我正在使用 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> Control Web Server</h1>";
    buf=buf.."<p> Press the button attached to the device and click below</p>"
    buf=buf.."<p><button onclick=\"history.go(0)\">ADVANCE</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.." not found - 404 error.<BR><a href='index.htm'/<%= @a %>>Home</a><BR>")
    end
    client:close();
    collectgarbage();
    f = nil
    tgtfile = nil
end)
end)

【问题讨论】:

  • 你使用的是什么版本的 NodeMCU?
  • 开发板是devkit 1.0。我正在使用自定义固件 1.5.4.1

标签: session lua webserver nodemcu


【解决方案1】:

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

您必须以某种方式编写代码,使其全部位于同一个 srv:listen() 函数中,并将有关客户端的某些信息(他们的 IP、cookie 或其他东西)存储在一个数组中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2017-06-09
    • 2019-01-12
    • 2021-06-18
    • 2021-08-19
    • 2021-09-07
    • 2021-05-28
    相关资源
    最近更新 更多