message.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from frame import Frame, OPCODE_TEXT, OPCODE_BINARY
  2. __all__ = ['Message', 'TextMessage', 'BinaryMessage']
  3. class Message(object):
  4. def __init__(self, opcode, payload):
  5. self.opcode = opcode
  6. self.payload = payload
  7. def frame(self, mask=False):
  8. return Frame(self.opcode, self.payload, mask=mask)
  9. def fragment(self, fragment_size, mask=False):
  10. return self.frame().fragment(fragment_size, mask)
  11. def __str__(self):
  12. return '<%s opcode=0x%X size=%d>' \
  13. % (self.__class__.__name__, self.opcode, len(self.payload))
  14. class TextMessage(Message):
  15. def __init__(self, payload):
  16. super(TextMessage, self).__init__(OPCODE_TEXT, payload.encode('utf-8'))
  17. class BinaryMessage(Message):
  18. def __init__(self, payload):
  19. super(BinaryMessage, self).__init__(OPCODE_BINARY, payload)
  20. OPCODE_CLASS_MAP = {
  21. OPCODE_TEXT: TextMessage,
  22. OPCODE_BINARY: BinaryMessage,
  23. }
  24. def create_message(opcode, payload):
  25. if opcode in OPCODE_CLASS_MAP:
  26. return OPCODE_CLASS_MAP[opcode](payload)
  27. return Message(opcode, payload)