httpserver-connection.lua 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. -- httpserver-connection
  2. -- Part of nodemcu-httpserver, provides a buffered connection object that can handle multiple
  3. -- consecutive send() calls.
  4. -- For this to work, it must be used from a coroutine.
  5. -- Author: Philip Gladstone, Marcos Kirsch
  6. BufferedConnection = {}
  7. -- parameter is the nodemcu-firmware connection
  8. function BufferedConnection:new(connection)
  9. local newInstance = {}
  10. newInstance.connection = connection
  11. newInstance.size = 0
  12. newInstance.data = {}
  13. function newInstance:flush()
  14. if self.size > 0 then
  15. self.connection:send(table.concat(self.data, ""))
  16. self.data = {}
  17. self.size = 0
  18. return true
  19. end
  20. return false
  21. end
  22. --@TODO What are the hardcoded 1000 and 800 about? Can we increase?
  23. function newInstance:send(payload)
  24. local l = payload:len()
  25. if l + self.size > 1000 then
  26. if self:flush() then
  27. coroutine.yield()
  28. end
  29. end
  30. if l > 800 then
  31. self.connection:send(payload)
  32. coroutine.yield()
  33. else
  34. table.insert(self.data, payload)
  35. self.size = self.size + l
  36. end
  37. end
  38. return newInstance
  39. end
  40. return BufferedConnection