httpserver-connection.lua 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. -- httpserver-connection
  2. -- Part of nodemcu-httpserver, provides a buffered connection object that can handle multiple
  3. -- consecutive send() calls, and buffers small payloads to send once they get big.
  4. -- For this to work, it must be used from a coroutine and owner is responsible for the final
  5. -- flush() and for closing the connection.
  6. -- Author: Philip Gladstone, Marcos Kirsch
  7. BufferedConnection = {}
  8. -- parameter is the nodemcu-firmware connection
  9. function BufferedConnection:new(connection)
  10. local newInstance = {}
  11. newInstance.connection = connection
  12. newInstance.size = 0
  13. newInstance.data = {}
  14. function newInstance:flush()
  15. if self.size > 0 then
  16. self.connection:send(table.concat(self.data, ""))
  17. self.data = {}
  18. self.size = 0
  19. return true
  20. end
  21. return false
  22. end
  23. function newInstance:send(payload)
  24. local l = payload:len()
  25. if l + self.size > 1024 then
  26. -- Send what we have buffered so far, not including payload.
  27. if self:flush() then
  28. coroutine.yield()
  29. end
  30. end
  31. if l > 768 then
  32. -- Payload is big. Send it now rather than buffering it for later.
  33. self.connection:send(payload)
  34. coroutine.yield()
  35. else
  36. -- Payload is small. Save off payload for later sending.
  37. table.insert(self.data, payload)
  38. self.size = self.size + l
  39. end
  40. end
  41. return newInstance
  42. end
  43. return BufferedConnection