NodeMCU HTTP服务器停止响应

时间:2016-05-01 09:18:56

标签: lua esp8266 nodemcu

我试图用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)

我做过的一些事情:

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

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

1 个答案:

答案 0 :(得分:2)

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

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

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

所以,这是on("sent")的完整示例。请注意,我将favicon更改为外部资源。如果你使用&#34; /&#34;浏览器仍会针对您的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)