其他发帖者已经提供了很多很好的信息,但我认为目前还没有针对这个问题给出好的具体解决方案,即使在非官方的常见问题解答中也是如此。
要发送大型静态文件,您可以从闪存加载它们并使用回调将它们分块发送。正如其他人所提到的,一个电话可以发送多少是有限制的。并且单个回调中的多个发送调用可能无法按您的预期处理,并且可能占用太多内存。这是一个以块的形式加载和发送文件的简短示例:
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)