memory-management - ESP8266 NodeMCU 内存不足
问题描述
NodeMCU 信息
> Lua 5.1.4
> SDK 2.2.1
> Memory Usage :
> Total : 3260490 bytes
> Used : 9287 bytes
> Remain: 3251203 bytes
当我尝试使用大 json 字符串响应发送 HTTP 响应时出现错误(json_response
)
PANIC: unprotected error in call to Lua API (file.lua:5: out of memory)
代码:
-- a simple HTTP server
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)
解决方案
是的,如果您尝试发送大量数据,这将不起作用。您需要逐个发送。我们的 API 文档显示了两种方法(您会在 SO 上找到更多参考资料),第一种是:
srv = net.createServer(net.TCP)
function receiver(sck, data)
local response = {}
-- if you're sending back HTML over HTTP you'll want something like this instead
-- local response = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"}
response[#response + 1] = "lots of data"
response[#response + 1] = "even more data"
response[#response + 1] = "e.g. content read from a file"
-- sends and removes the first element from the 'response' table
local function send(localSocket)
if #response > 0 then
localSocket:send(table.remove(response, 1))
else
localSocket:close()
response = nil
end
end
-- triggers the send() function again once the first chunk of data was sent
sck:on("sent", send)
send(sck)
end
srv:listen(80, function(conn)
conn:on("receive", receiver)
end)
推荐阅读
- java - 程序无法识别 .class 文件
- javascript - 如何在Javascript中选择动态生成的元素
- python - 如何使用 Beautifulsoup 将兄弟元素附加到前一个元素
- java - 如何在不破坏基于 ASCII 的代码的情况下增加 US ASCII 字符集的范围?
- python - tree.xpath() 使用 lxml 库在 Webscraping 中返回空列表
- javascript - 在 react/redux/reach 路由器应用程序中进行 API 调用的最佳位置在哪里?
- c# - .Net Core 3.0 Angular 应用程序发布请求参数始终为 NULL
- reactjs - 无法在 ubuntu 操作系统中使用 npm 安装 expo-cli?
- javascript - React hook 不会立即渲染
- python - 在任何终端执行 get-pip.py 什么都不输出