gpt4 book ai didi

html - 如何发送多个数据(conn :send()) with the new SDK (NodeMCU)

转载 作者:搜寻专家 更新时间:2023-10-31 23:23:16 25 4
gpt4 key购买 nike

我一直在阅读 NodeMCU 文档和几个关于 SDK 更改的已解决问题,这些更改以前允许发送多个数据流(就像排队的 net.socket:send)。

这里 ( #730 ) 和那里 ( #993 ) 甚至这里 ( #999 ) 似乎都展开了激烈的争论。但是,我没有找到任何令人信服的网络服务器代码示例,该代码允许我读取多个 html 文件(例如 head.htmlbody.html)来显示页面.这是我尝试改编但没有成功的 TerryE 示例:

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on ("receive", function(sck, req)
local response = {}

local f = file.open("head.html","r")
if f ~= nil then
response[#response+1] = file.read()
file.close()
end

local f = file.open("body.html","r")
if f ~= nil then
response[#response+1] = file.read()
file.close()
end

local function sender (sck)
if #response>0 then sck:send(table.remove(response,1))
else sck:close()
end
end
sck:on("sent", sender)
sender(sck)
end )
end )

当连接到 ESP8266 时,没有任何加载,我从 lua 终端没有收到任何错误。

供您引用,head.html 包含:

<html>
<head>
</head>

body.html 包含:

<body>
<h1>Hello World</h1>
</body>
</html>

我是NodeMCU新手,请多多包涵。

最佳答案

这是我不使用表格的解决方案,节省了一些内存:

function Sendfile(sck, filename, sentCallback)
if not file.open(filename, "r") then
sck:close()
return
end
local function sendChunk()
local line = file.read(512)
if line then
sck:send(line, sendChunk)
else
file.close()
collectgarbage()
if sentCallback then
sentCallback()
else
sck:close()
end
end
end
sendChunk()
end


srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(sck, req)
sck:send("HTTP/1.1 200 OK\r\n" ..
"Server: NodeMCU on ESP8266\r\n" ..
"Content-Type: text/html; charset=UTF-8\r\n\r\n",
function()
Sendfile(sck, "head.html", function() Sendfile(sck, "body.html") end)
end)
end)
end)

这是为单个文件提供服务:

function Sendfile(client, filename)
if file.open(filename, "r") then
local function sendChunk()
local line = file.read(512)
if line then
client:send(line, sendChunk)
else
file.close()
client:close()
collectgarbage()
end
end
client:send("HTTP/1.1 200 OK\r\n" ..
"Server: NodeMCU on ESP8266\r\n" ..
"Content-Type: text/html; charset=UTF-8\r\n\r\n", sendChunk)
else
client:send("HTTP/1.0 404 Not Found\r\n\r\nPage not found")
client:close()
end
end


srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on ("receive", function(client, request)
local path = string.match(request, "GET /(.+) HTTP")
if path == "" then path = "index.htm" end
Sendfile(client, path)
end)
end)

关于html - 如何发送多个数据(conn :send()) with the new SDK (NodeMCU),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36079145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com