Lua NodeMCU Web服务器是否在第一次发送后关闭连接?
我的ESP-12上有一个小型web服务器,带有nodemcu固件:Lua NodeMCU Web服务器是否在第一次发送后关闭连接?,lua,nodemcu,Lua,Nodemcu,我的ESP-12上有一个小型web服务器,带有nodemcu固件: sv=net.createServer(net.TCP,10) sv:listen(80,function(c) c:on("receive", function(c, pl) if(string.find(pl,"GET / ")) then print("Asking for index") c:send("Line 1")
sv=net.createServer(net.TCP,10)
sv:listen(80,function(c)
c:on("receive", function(c, pl)
if(string.find(pl,"GET / ")) then
print("Asking for index")
c:send("Line 1")
c:send("Line 2")
c:send("Line 3")
c:close()
end
end)
c:on("sent",function(conn)
print("sended something...")
end)
end)
似乎我的连接在第一次发送后就被关闭了,在我的浏览器中我只看到“line 1”文本,line 2 a 3没有出现,在我的串行控制台中,我只看到了“sended something”文本一次,甚至对close语句进行注释并让连接超时也不会改变行为。我在这里遗漏了什么?我认为您不能多次使用发送。每当我使用ESP8266中的一个作为服务器时,我都会使用一个缓冲区变量:
sv=net.createServer(net.TCP,10)
-- 'c' -> connection, 'pl' -> payload
sv:listen(80,function(c)
c:on("receive", function(c, pl)
if(string.find(pl,"GET / ")) then
print("Asking for index")
local buffer = ""
buffer = buffer.."Line 1"
buffer = buffer.."Line 2"
buffer = buffer.."Line 3"
c:send(buffer)
c:close()
end
end)
c:on("sent",function(c)
print("sended something...")
end)
end)
编辑:再次阅读文档后,可以使用回调函数获取另一个参数,它可能用于具有多个send命令。但从未尝试过:(
编辑2:如果要发送一个很长的字符串,最好使用文档提供了一个很好的示例,我在这里重复
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)
我不久前使用了缓冲区解决方案,它可以工作,但问题是如果你必须缓冲一个大文件,你就有可能内存不足。也许是回调工作的想法,我会尝试一下。谢谢你确实我应该想到这一点(我曾经遇到过这个问题)。我修改了我的答案,添加了关于表的注释。concatt此问题是内存泄漏,因为回调函数重新使用了
c
。我将添加其他答案,有关相关问题,请参阅和。