WebServer.py 3.1 KB

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