WebServer.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import asyncio
  2. import datetime
  3. import re
  4. import websockets
  5. import logging
  6. import threading
  7. from pokermaster.PokerMasterDataProccesser import deal_message
  8. logging.basicConfig(level=logging.INFO)
  9. ip = "192.168.137.1"
  10. port = 9999
  11. connected_clients = set()
  12. async def echo(websocket, path):
  13. connected_clients.add(websocket)
  14. try:
  15. async for message in websocket:
  16. # with open("ws.log", "a") as f:
  17. # time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  18. # f.write(f"{time}:{message}\n")
  19. await deal_message(message, broadcast)
  20. await websocket.send("Server says: 你好,服务端收到,连接建立成功")
  21. except websockets.ConnectionClosed as e:
  22. logging.warning(f"Connection closed: {e.reason}")
  23. except Exception as e:
  24. logging.error(f"Error: {e}", exc_info=True)
  25. finally:
  26. connected_clients.remove(websocket)
  27. async def broadcast(message):
  28. if connected_clients:
  29. await asyncio.wait([client.send(message) for client in connected_clients])
  30. else:
  31. print("No clients are connected.")
  32. def start_cli(loop):
  33. while True:
  34. # Enter command (1: Send custom message, 2: Send JS script from file): 翻译成中文并且print
  35. print("输入命令 (1: 发送自定义消息, 2: 发送JS脚本):")
  36. command = input("请输入:")
  37. if command == "1":
  38. message = input("Enter message to send: ")
  39. # 在当前运行的事件循环中安排broadcast任务
  40. loop.call_soon_threadsafe(asyncio.create_task, broadcast(message))
  41. elif command == "2":
  42. sendJsCommand(loop)
  43. else:
  44. print("Unknown command")
  45. def sendJsCommand(loop):
  46. with open("script.js", "r", encoding="utf-8") as file:
  47. script_content = file.read()
  48. # 去除script中注释的行注释或者块注释
  49. script_content = re.sub(r"//.*?$", "", script_content, flags=re.MULTILINE) # 去除行注释
  50. script_content = re.sub(r"/\*.*?\*/", "", script_content, flags=re.DOTALL) # 去除块注释
  51. # 可选:移除因为删除注释而产生的多余空行
  52. script_content = re.sub(r"\n\s*\n", "\n", script_content, flags=re.MULTILINE)
  53. # 在当前运行的事件循环中安排broadcast任务
  54. loop.call_soon_threadsafe(asyncio.create_task, broadcast(script_content))
  55. async def main():
  56. server = await websockets.serve(echo, ip, port)
  57. try:
  58. await server.wait_closed()
  59. except KeyboardInterrupt:
  60. logging.info("Server stopped by KeyboardInterrupt")
  61. if __name__ == '__main__':
  62. now = datetime.datetime.now()
  63. cache_date = now.strftime("%Y-%m-%d")
  64. cache_hour = now.strftime("%H")
  65. loop = asyncio.get_event_loop()
  66. # 在另一个线程中启动 CLI
  67. cli_thread = threading.Thread(target=start_cli, args=(loop,), daemon=True)
  68. cli_thread.start()
  69. try:
  70. loop.run_until_complete(main())
  71. except Exception as e:
  72. logging.error(f"Server error: {e}", exc_info=True)
  73. finally:
  74. loop.close()