stateful.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- test-case-name: twisted.test.test_stateful -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. from twisted.internet import protocol
  5. from io import BytesIO
  6. class StatefulProtocol(protocol.Protocol):
  7. """A Protocol that stores state for you.
  8. state is a pair (function, num_bytes). When num_bytes bytes of data arrives
  9. from the network, function is called. It is expected to return the next
  10. state or None to keep same state. Initial state is returned by
  11. getInitialState (override it).
  12. """
  13. _sful_data = None, None, 0
  14. def makeConnection(self, transport):
  15. protocol.Protocol.makeConnection(self, transport)
  16. self._sful_data = self.getInitialState(), BytesIO(), 0
  17. def getInitialState(self):
  18. raise NotImplementedError
  19. def dataReceived(self, data):
  20. state, buffer, offset = self._sful_data
  21. buffer.seek(0, 2)
  22. buffer.write(data)
  23. blen = buffer.tell() # how many bytes total is in the buffer
  24. buffer.seek(offset)
  25. while blen - offset >= state[1]:
  26. d = buffer.read(state[1])
  27. offset += state[1]
  28. next = state[0](d)
  29. if self.transport.disconnecting: # XXX: argh stupid hack borrowed right from LineReceiver
  30. return # dataReceived won't be called again, so who cares about consistent state
  31. if next:
  32. state = next
  33. if offset != 0:
  34. b = buffer.read()
  35. buffer.seek(0)
  36. buffer.truncate()
  37. buffer.write(b)
  38. offset = 0
  39. self._sful_data = state, buffer, offset