message.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import json
  2. from frame import Frame, OPCODE_TEXT, OPCODE_BINARY
  3. __all__ = ['Message', 'TextMessage', 'BinaryMessage', 'JSONMessage']
  4. class Message(object):
  5. def __init__(self, opcode, payload):
  6. self.opcode = opcode
  7. self.payload = payload
  8. def frame(self, mask=False):
  9. return Frame(self.opcode, self.payload, mask=mask)
  10. def fragment(self, fragment_size, mask=False):
  11. return self.frame().fragment(fragment_size, mask)
  12. def __str__(self):
  13. return '<%s opcode=0x%X size=%d>' \
  14. % (self.__class__.__name__, self.opcode, len(self.payload))
  15. class TextMessage(Message):
  16. def __init__(self, payload):
  17. super(TextMessage, self).__init__(OPCODE_TEXT, payload.encode('utf-8'))
  18. class BinaryMessage(Message):
  19. def __init__(self, payload):
  20. super(BinaryMessage, self).__init__(OPCODE_BINARY, payload)
  21. class JSONMessage(TextMessage):
  22. def __init__(self, data, **kwargs):
  23. self.data = {}
  24. self.data.update(data, **kwargs)
  25. super(JSONMessage, self).__init__(json.dumps(self.data))
  26. @classmethod
  27. def decode(cls, payload):
  28. return cls(json.loads(payload))
  29. def create_message(opcode, payload):
  30. if opcode == OPCODE_TEXT:
  31. return TextMessage(payload)
  32. if opcode == OPCODE_BINARY:
  33. return BinaryMessage(payload)
  34. return Message(opcode, payload)