base_strategy.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. 基础策略类
  3. """
  4. from utils.logger import logger
  5. from abc import abstractmethod, ABC
  6. from typing import Union, Tuple
  7. class ProcessStrategy(ABC):
  8. """处理策略基类"""
  9. def makepacket(self, sid: int, msg_type: int, content: Union[str, bytes]) -> bytearray:
  10. """
  11. 构建消息包
  12. Args:
  13. sid: 会话ID
  14. msg_type: 消息类型
  15. content: 消息内容
  16. Returns:
  17. bytearray: 完整的消息包
  18. """
  19. if isinstance(content, str):
  20. content = content.encode('utf-8')
  21. size = len(content)
  22. temp = bytearray()
  23. temp.append(0xa5) # 同步头
  24. temp.append(0x01) # 用户ID
  25. temp.append(msg_type) # 消息类型
  26. temp.append(size & 0xff) # 长度低字节
  27. temp.append((size >> 8) & 0xff) # 长度高字节
  28. temp.append(sid & 0xff) # 会话ID低字节
  29. temp.append((sid >> 8) & 0xff) # 会话ID高字节
  30. temp.extend(content) # 消息内容
  31. temp.append(self.checkcode(temp)) # 校验码
  32. return temp
  33. def checkcode(self, data: bytearray) -> int:
  34. """
  35. 计算校验码
  36. Args:
  37. data: 数据字节数组
  38. Returns:
  39. int: 校验码
  40. """
  41. total = sum(data)
  42. checkcode = (~total + 1) & 0xFF
  43. return checkcode
  44. @abstractmethod
  45. def process(self, client_socket, data) -> Union[bool, Tuple[bool, bytes]]:
  46. """
  47. 处理消息的抽象方法
  48. Args:
  49. client_socket: 客户端socket
  50. data: 要处理的数据
  51. Returns:
  52. Union[bool, Tuple[bool, bytes]]: 处理结果
  53. """
  54. pass