httpserver-static.lua 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. -- httpserver-static.lua
  2. -- Part of nodemcu-httpserver, handles sending static files to client.
  3. -- Author: Marcos Kirsch
  4. return function (connection, req, args)
  5. dofile("httpserver-header.lc")(connection, 200, args.ext, args.gzipped)
  6. --print("Begin sending:", args.file)
  7. -- Send file in little chunks
  8. local continue = true
  9. local size = file.list()[args.file]
  10. local bytesSent = 0
  11. local chunkSize = 1024 -- @TODO: can chunkSize be larger?
  12. while continue do
  13. collectgarbage()
  14. -- NodeMCU file API lets you open 1 file at a time.
  15. -- So we need to open, seek, close each time in order
  16. -- to support multiple simultaneous clients.
  17. file.open(args.file)
  18. file.seek("set", bytesSent)
  19. local chunk = file.read(chunkSize)
  20. file.close()
  21. connection:send(chunk)
  22. bytesSent = bytesSent + #chunk
  23. chunk = nil
  24. --print("Sent: " .. bytesSent .. " of " .. size)
  25. -- nodemcu-firmware disallows queueing send operations,
  26. -- so we must call coroutine.yield() after every connection:send()
  27. -- The onSent() will resume us. But only yield if we aren't done yet!
  28. if bytesSent == size then continue = false else coroutine.yield() end
  29. end
  30. --print("Finished sending: ", args.file)
  31. end