message.py 1.3 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, dictionary, **kwargs):
  23. self.data = {}
  24. self.data.extend(dictionary)
  25. self.data.extend(kwargs)
  26. super(JSONMessage, self).__init__(json.dumps(self.data))
  27. OPCODE_CLASS_MAP = {
  28. OPCODE_TEXT: TextMessage,
  29. OPCODE_BINARY: BinaryMessage,
  30. }
  31. def create_message(opcode, payload):
  32. if opcode in OPCODE_CLASS_MAP:
  33. return OPCODE_CLASS_MAP[opcode](payload)
  34. return Message(opcode, payload)