#!/usr/bin/env python3

import asyncio
import websockets
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(message)s')

async def listen_to_server(uri, reconnect_interval=3):
    """
    连接到 WebSocket 服务器并持续监听消息。
    如果连接断开，将自动尝试重连。
    
    :param uri: WebSocket 地址
    :param reconnect_interval: 重连间隔（秒）
    """
    while True:
        try:
            async with websockets.connect(uri) as websocket:
                logging.info(f"✅ 已成功连接到 {uri}")
                
                # 持续接收消息
                async for message in websocket:
                    logging.info(f"📩 收到消息: {message}")
        
        except websockets.exceptions.ConnectionClosed as e:
            logging.warning(f"⚠️ 与服务器的连接已关闭: {e}. {reconnect_interval} 秒后尝试重连...")
        
        except ConnectionRefusedError:
            logging.error(f"❌ 无法连接到服务器 {uri}（连接被拒绝）。检查服务器是否运行。")
            logging.info(f"🔁 {reconnect_interval} 秒后尝试重连...")
        
        except Exception as e:
            logging.error(f"🚨 发生未预期错误: {type(e).__name__}: {e}")
            logging.info(f"🔁 {reconnect_interval} 秒后尝试重连...")

        # 等待一段时间后尝试重连
        await asyncio.sleep(reconnect_interval)

async def main():
    uri = "ws://127.0.0.1:3030"
    await listen_to_server(uri, reconnect_interval=3)

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logging.info("👋 用户中断，程序退出。")