httpserver-buffer.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. -- httpserver-buffer
  2. -- Part of nodemcu-httpserver, provides a buffer that behaves like a connection object
  3. -- that can handle multiple consecutive send() calls, and buffers small payloads up to 1400 bytes.
  4. -- This is primarily user to collect the send requests done by the head script.
  5. -- The owner is responsible to call getBuffer and send its result
  6. -- Author: Gregor Hartmann
  7. local Buffer = {}
  8. -- parameter is the nodemcu-firmware connection
  9. function Buffer:new()
  10. local newInstance = {}
  11. newInstance.size = 0
  12. newInstance.data = {}
  13. -- Returns true if there was any data to be sent.
  14. function newInstance:getBuffer()
  15. local buffer = table.concat(self.data, "")
  16. self.data = {}
  17. self.size = 0
  18. return buffer
  19. end
  20. function newInstance:getpeer()
  21. return "no peer"
  22. end
  23. function newInstance:send(payload)
  24. local flushThreshold = 1400
  25. if (not payload) then print("nop payload") end
  26. local newSize = self.size + payload:len()
  27. if newSize >= flushThreshold then
  28. print("Buffer is full. Cutting off "..newSize-flushThreshold.." chars")
  29. --STEP1: cut out piece from payload to complete threshold bytes in table
  30. local pieceSize = flushThreshold - self.size
  31. if pieceSize then
  32. payload = payload:sub(1, pieceSize)
  33. end
  34. end
  35. table.insert(self.data, payload)
  36. self.size = self.size + #payload
  37. end
  38. return newInstance
  39. end
  40. return Buffer