import asyncio import datetime import re import websockets import logging import threading from pokermaster.PokerMasterDataProccesser import deal_message, write_message_2_log_file logging.basicConfig(level=logging.INFO) ip = "192.168.137.1" port = 9999 # 从同目录下读取props.properties文件,获取配置(ip、port)信息 with open("../props.properties", "r") as f: props = f.readlines() for prop in props: if prop.startswith("ip"): ip = prop.split("=")[1].strip() if prop.startswith("port"): port = prop.split("=")[1].strip() connected_clients = set() async def echo(websocket, path): connected_clients.add(websocket) try: async for message in websocket: # await write_message_2_log_file(message) await deal_message(message, broadcast) # print(f"Received message: {message}") await websocket.send("Server says: 你好,服务端收到,连接建立成功") except websockets.ConnectionClosed as e: logging.warning(f"Connection closed: {e.reason}") except Exception as e: logging.error(f"Error: {e}", exc_info=True) finally: connected_clients.remove(websocket) async def broadcast(message): if connected_clients: # 将协程转换为Task对象,并收集到一个列表中 tasks = [asyncio.create_task(client.send(message)) for client in connected_clients] # 等待所有任务完成 await asyncio.wait(tasks) else: print("No clients are connected.") def start_cli(loop): while True: # Enter command (1: Send custom message, 2: Send JS script from file): 翻译成中文并且print print("输入命令 (1: 发送自定义消息, 2: 发送JS脚本):") command = input("请输入:") if command == "1": message = input("Enter message to send: ") # 在当前运行的事件循环中安排broadcast任务 loop.call_soon_threadsafe(asyncio.create_task, broadcast(message)) elif command == "2": sendJsCommand(loop) else: print("Unknown command") def sendJsCommand(loop): with open("../script.js", "r", encoding="utf-8") as file: script_content = file.read() # 去除script中注释的行注释或者块注释 script_content = re.sub(r"//.*?$", "", script_content, flags=re.MULTILINE) # 去除行注释 script_content = re.sub(r"/\*.*?\*/", "", script_content, flags=re.DOTALL) # 去除块注释 # 可选:移除因为删除注释而产生的多余空行 script_content = re.sub(r"\n\s*\n", "\n", script_content, flags=re.MULTILINE) # 在当前运行的事件循环中安排broadcast任务 loop.call_soon_threadsafe(asyncio.create_task, broadcast(script_content)) async def main(): server = await websockets.serve(echo, ip, port) try: await server.wait_closed() except KeyboardInterrupt: logging.info("Server stopped by KeyboardInterrupt") if __name__ == '__main__': now = datetime.datetime.now() cache_date = now.strftime("%Y-%m-%d") cache_hour = now.strftime("%H") loop = asyncio.get_event_loop() # 在另一个线程中启动 CLI cli_thread = threading.Thread(target=start_cli, args=(loop,), daemon=True) cli_thread.start() try: loop.run_until_complete(main()) except Exception as e: logging.error(f"Server error: {e}", exc_info=True) finally: loop.close()