【问题标题】:NodeMCU HTTP server stops respondingNodeMCU HTTP 服务器停止响应
【发布时间】:2016-06-10 13:08:50
【问题描述】:

我正在尝试使用 NodeMCU 制作一个简单的 HTTP 服务器。我启动nodeMCU,然后将它连接到wifi,然后运行下面的程序。我可以从我的浏览器连接到服务器。如果我继续重新加载页面,它将永远工作,但是当我停止发送请求一两分钟时,服务器会以某种方式停止运行。这意味着,当我重新加载页面时,nodeMCU 没有收到任何数据(并且无法返回任何数据)。

a=0

function receive(conn,payload) 
    a=a+1
    print(payload) 

    local content="<!DOCTYPE html><html><head><link rel='shortcut icon' href='/'></head><body><h1>Hello!</h1><p>Since the start of the server " .. a .. " connections were made</p></body></html>"
    local contentLength=string.len(content)

    conn:send("HTTP/1.1 200 OK\r\nContent-Length:" .. contentLength .. "\r\n\r\n" .. content)
    conn:close()
end

function connection(conn) 
    conn:on("receive",receive)
end

srv=net.createServer(net.TCP,1) 
srv:listen(8080,connection)

我做过的一些事情:

  • 我已通过将链接添加到任何内容来阻止浏览器请求网站图标。
  • 我将非活动客户端的超时设置为 1,以防止浏览器长时间加载(浏览器一直加载直到超时)。
  • 我更新了代码以发送一些 HTTP 标头。
  • 我尝试在每次连接后关闭和打开服务器(不好,因为如果您继续进行连接,即使没有此修复,它也永远不会停止工作)。
  • 我按照 StackOverflow 上的答案建议添加了 conn:close()

我正在运行预编译固件 0.9.6-dev_20150704 整数。

【问题讨论】:

    标签: lua esp8266 nodemcu


    【解决方案1】:

    首先,您不应该使用那些旧的 0.9.x 二进制文件。它们不再受支持,并且包含许多错误。从 dev (1.5.1) 或 master (1.4) 分支构建自定义固件:http://nodemcu.readthedocs.io/en/dev/en/build/

    使用 SDK 的 >1.0 版本(如果您从当前分支构建,您会得到)conn:send 是完全异步的,即您不能连续多次调用它。此外,您不能在conn:send() 之后立即调用conn:close(),因为套接字可能会在send() 完成之前关闭。相反,您可以监听sent 事件并在其回调中关闭套接字。如果您考虑到这一点,您的代码可以在最新固件上正常运行。

    NodeMCU API docs for socket:send() 中记录了一种更优雅的异步发送方式。但是,该方法使用更多堆,对于像您这样的数据量很少的简单情况则没有必要。

    所以,这是on("sent") 的完整示例。请注意,我将网站图标更改为外部资源。如果您使用“/”,浏览器仍会向您的 ESP8266 发出额外请求。

    a = 0
    
    function receive(conn, payload)
        print(payload) 
        a = a + 1
    
        local content="<!DOCTYPE html><html><head><link rel='icon' type='image/png' href='http://nodemcu.com/favicon.png' /></head><body><h1>Hello!</h1><p>Since the start of the server " .. a .. " connections were made</p></body></html>"
        local contentLength=string.len(content)
    
        conn:on("sent", function(sck) sck:close() end)
        conn:send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length:" .. contentLength .. "\r\n\r\n" .. content)
    end
    
    function connection(conn) 
        conn:on("receive", receive)
    end
    
    srv=net.createServer(net.TCP, 1) 
    srv:listen(8080, connection)
    

    【讨论】:

    • 虽然我还没试过,但你的回答完美解决了我的问题,可能是旧固件的问题。
    • 好的,我现在正在运行一个新固件,我刚刚发现服务器停止响应的问题可能是由我的 WiFi AP 引起的……我的平板电脑定期断开连接时遇到了一些问题。现在我尝试了几次断开WiFi并在服务器停止响应并且服务器再次运行之后再次连接。
    • 这实际上是我的第一个猜测......直到我看到你正在运行 NodeMCU 0.9.6。
    • 我通过连接静态 IP 解决了我的平板电脑问题,但对于 nodeMCU 它没有解决任何问题,所以我所做的是我使用 nodeMCU 作为 AP,它工作得很好(当然现在无法访问互联网)
    • wifi.sta.config 使用auto=1,对吗? nodemcu.readthedocs.io/en/dev/en/modules/wifi/#wifistaconfig
    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    相关资源
    最近更新 更多