WebServer.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import asyncio
  2. import datetime
  3. import json
  4. import re
  5. import websockets
  6. import logging
  7. import threading
  8. logging.basicConfig(level=logging.INFO)
  9. ip = "192.168.137.1"
  10. port = 9999
  11. connected_clients = set()
  12. def parse_message(message):
  13. # 分割消息类型和JSON字符串
  14. msg_type, json_str = message.split(':', 1)
  15. # 将JSON字符串转换为字典
  16. data = json.loads(json_str)
  17. # 返回解析结果
  18. return msg_type, data
  19. async def deal_message(message):
  20. try:
  21. msg_type, data = parse_message(message)
  22. if msg_type == "BetNotify":
  23. print(f"下注: {data}")
  24. elif msg_type == "GameDataSynNotify":
  25. print(f"同步游戏数据: {data}")
  26. elif msg_type == "KickNotify":
  27. print(f"被踢下线了: {data}")
  28. await broadcast('''CMD:
  29. setTimeout(function(){
  30. let btnDownNode = cc.find("Layer/PushNotice_panel/close_button");
  31. if (btnDownNode && btnDownNode.getComponent(cc.Button)) {
  32. btnDownNode.getComponent(cc.Button).clickEvents[0].emit([btnDownNode]);
  33. } else {
  34. console.error("节点未找到或节点上没有cc.Button组件");
  35. }
  36. },3000);
  37. setTimeout(function(){
  38. let btnDownNode = cc.find("Canvas/container/content/smallGame/createScrollView/view/cotent/row1/pokerNode/porkermaster/allHand");
  39. if (btnDownNode && btnDownNode.getComponent(cc.Button)) {
  40. btnDownNode.getComponent(cc.Button).clickEvents[0].emit([btnDownNode]);
  41. } else {
  42. console.error("节点未找到或节点上没有cc.Button组件");
  43. }
  44. },6000);
  45. ''')
  46. else:
  47. logging.info(f"Received message: {message}")
  48. except json.JSONDecodeError as e:
  49. logging.error(f"Error decoding JSON: {e}")
  50. except Exception as e:
  51. logging.info(f"Received message: {message}")
  52. async def echo(websocket, path):
  53. connected_clients.add(websocket)
  54. try:
  55. async for message in websocket:
  56. with open("ws.log", "a") as f:
  57. time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  58. f.write(f"{time}:{message}\n")
  59. await deal_message(message)
  60. await websocket.send("Server says: 你好,服务端收到,连接建立成功")
  61. except websockets.ConnectionClosed as e:
  62. logging.warning(f"Connection closed: {e.reason}")
  63. except Exception as e:
  64. logging.error(f"Error: {e}", exc_info=True)
  65. finally:
  66. connected_clients.remove(websocket)
  67. async def broadcast(message):
  68. if connected_clients:
  69. await asyncio.wait([client.send(message) for client in connected_clients])
  70. else:
  71. print("No clients are connected.")
  72. def start_cli(loop):
  73. while True:
  74. # Enter command (1: Send custom message, 2: Send JS script from file): 翻译成中文并且print
  75. print("输入命令 (1: 发送自定义消息, 2: 发送JS脚本):")
  76. command = input("请输入:")
  77. if command == "1":
  78. message = input("Enter message to send: ")
  79. # 在当前运行的事件循环中安排broadcast任务
  80. loop.call_soon_threadsafe(asyncio.create_task, broadcast(message))
  81. elif command == "2":
  82. sendJsCommand(loop)
  83. else:
  84. print("Unknown command")
  85. def sendJsCommand(loop):
  86. with open("script.js", "r", encoding="utf-8") as file:
  87. script_content = file.read()
  88. # 去除script中注释的行注释或者块注释
  89. script_content = re.sub(r"//.*?$", "", script_content, flags=re.MULTILINE) # 去除行注释
  90. script_content = re.sub(r"/\*.*?\*/", "", script_content, flags=re.DOTALL) # 去除块注释
  91. # 可选:移除因为删除注释而产生的多余空行
  92. script_content = re.sub(r"\n\s*\n", "\n", script_content, flags=re.MULTILINE)
  93. # 在当前运行的事件循环中安排broadcast任务
  94. loop.call_soon_threadsafe(asyncio.create_task, broadcast(script_content))
  95. async def main():
  96. server = await websockets.serve(echo, ip, port)
  97. try:
  98. await server.wait_closed()
  99. except KeyboardInterrupt:
  100. logging.info("Server stopped by KeyboardInterrupt")
  101. if __name__ == '__main__':
  102. loop = asyncio.get_event_loop()
  103. # 在另一个线程中启动 CLI
  104. cli_thread = threading.Thread(target=start_cli, args=(loop,), daemon=True)
  105. cli_thread.start()
  106. try:
  107. loop.run_until_complete(main())
  108. except Exception as e:
  109. logging.error(f"Server error: {e}", exc_info=True)
  110. finally:
  111. loop.close()