ESP8266 NodeMCU内存不足

NodeMCU信息

> Lua 5.1.4
> SDK 2.2.1
> 内存使用情况:
> 总计:3260490字节
> 已用:9287字节
> 剩余:3251203字节

当我尝试发送带有大型JSON字符串响应(json_response)的HTTP响应时,我得到了以下错误

PANIC:在调用Lua API时出现未保护的错误(file.lua:5:内存不足)

代码:

  -- 一个简单的HTTP服务器
    srv = net.createServer(net.TCP)
    srv:listen(80, function(conn)
        conn:on("receive", function(sck, payload)
            sck:send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n"..json_response)
        end)
        conn:on("sent", function(sck) sck:close() end)
    end)
点赞
用户131929
用户131929

是的,如果您尝试发送大量数据,这将行不通。您需要逐个发送。我们的 API 文档显示了两种方法(您可以在此处找到更多引用),第一种方法如下:

srv = net.createServer(net.TCP)

function receiver(sck, data)
  local response = {}

  -- 如果您要通过HTTP回送HTML,您需要像这样编写
  -- local response = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"}

  response[#response + 1] = "大量数据"
  response[#response + 1] = "更多的数据"
  response[#response + 1] = "例如从文件读取的内容"

  -- 发送并从'response'表中删除第一个元素
  local function send(localSocket)
    if #response > 0 then
      localSocket:send(table.remove(response, 1))
    else
      localSocket:close()
      response = nil
    end
  end

  -- 在第一块数据发送后再次触发send()函数
  sck:on("sent", send)

  send(sck)
end

srv:listen(80, function(conn)
  conn:on("receive", receiver)
end)
2018-08-10 22:03:01