其他海报提供了很多很好的信息,但我认为即使在非正式的常见问题解答中,也没有给出这个问题的特定解决方案。
要发送大型静态文件,您可以使用回调从闪存中加载它们并以块的形式发送它们。正如其他人所提到的,一次通话可以发送多少是有限的。单个回调中的多个发送调用可能无法按预期处理,并且可能占用太多内存。这是一个以块的形式加载和发送文件的简短示例:
local idx = 0 --keep track of where we are in the file
local fname = "index.html"
function nextChunk(c) --open file, read a chunk, and send it!
file.open(fname)
file.seek("set", idx)
local str = file.read(500)
if not str then return end --no more to send.
c:send(str)
idx = idx + 500
file.close() --close the file to let other callbacks use the filesystem
end
client:on("sent", nextChunk) --every time we send a chunk, start the next one!
nextChunk(client) --send the first chunk.或者,使用协同程序和计时器,我们可以使它更灵活:
local ready = true --represents whether we are ready to send again
client:on("sent", function() ready=true end) --we are ready after sending the previous chunk is finished.
local function sendFile(fname)
local idx=0 --keep track of where we are in the file
while true do
file.open(fname)
file.seek("set", idx)
local str = file.read(500)
if not str then return end --no more to send.
c:send(str)
ready=false --we have sent something. we are no longer ready.
idx = idx + 500
file.close() --close the file to let other callbacks use the filesystem
coroutine.yield() --give up control to the caller
end
end
local sendThread = coroutine.create(sendFile)
tmr.alarm(0, 100, 1, function() --make a repeating alarm that will send the file chunk-by-chunk
if ready then coroutine.resume(sendThread, "index.html") end
if coroutine.status(sendThread) == "dead" then tmr.stop(0) end --stop when we are done
end)