diff --git a/src/plugins/remote/__init__.py b/src/plugins/remote/__init__.py index 7a4a88472..02b19518a 100644 --- a/src/plugins/remote/__init__.py +++ b/src/plugins/remote/__init__.py @@ -1,4 +1,5 @@ import asyncio from .remote import main -asyncio.run(main()) +# 启动心跳线程 +heartbeat_thread = main() diff --git a/src/plugins/remote/remote.py b/src/plugins/remote/remote.py index f2741b222..6020398e8 100644 --- a/src/plugins/remote/remote.py +++ b/src/plugins/remote/remote.py @@ -4,13 +4,12 @@ import uuid import platform import os import json +import threading from loguru import logger -import asyncio # UUID文件路径 UUID_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "client_uuid.json") - # 生成或获取客户端唯一ID def get_unique_id(): # 检查是否已经有保存的UUID @@ -37,7 +36,6 @@ def get_unique_id(): return client_id - # 生成客户端唯一ID def generate_unique_id(): # 结合主机名、系统信息和随机UUID生成唯一ID @@ -45,7 +43,6 @@ def generate_unique_id(): unique_id = f"{system_info}-{uuid.uuid4()}" return unique_id - def send_heartbeat(server_url, client_id): """向服务器发送心跳""" sys = platform.system() @@ -66,31 +63,40 @@ def send_heartbeat(server_url, client_id): logger.debug(f"发送心跳时出错: {e}") return False - -async def main(): - # 配置 - SERVER_URL = "http://hyybuth.xyz:10058" # 更改为你的服务器地址 - HEARTBEAT_INTERVAL = 300 # 5分钟(秒) - - # 获取或生成客户端ID - client_id = get_unique_id() - logger.debug(f"客户端已启动,ID: {client_id}") - - # 主心跳循环 - try: - while True: - if send_heartbeat(SERVER_URL, client_id): - print(f"{HEARTBEAT_INTERVAL}秒后发送下一次心跳...") +class HeartbeatThread(threading.Thread): + """心跳线程类""" + + def __init__(self, server_url, interval): + super().__init__(daemon=True) # 设置为守护线程,主程序结束时自动结束 + self.server_url = server_url + self.interval = interval + self.client_id = get_unique_id() + self.running = True + + def run(self): + """线程运行函数""" + logger.debug(f"心跳线程已启动,客户端ID: {self.client_id}") + + while self.running: + if send_heartbeat(self.server_url, self.client_id): + logger.info(f"{self.interval}秒后发送下一次心跳...") else: - print(f"{HEARTBEAT_INTERVAL}秒后重试...") + logger.info(f"{self.interval}秒后重试...") + + time.sleep(self.interval) # 使用同步的睡眠 + + def stop(self): + """停止线程""" + self.running = False - await asyncio.sleep(HEARTBEAT_INTERVAL) - - except KeyboardInterrupt: - print("用户已停止客户端") - except Exception as e: - print(f"发生意外错误: {e}") - - -if __name__ == "__main__": - asyncio.run(main()) +def main(): + """主函数,启动心跳线程""" + # 配置 + SERVER_URL = "http://hyybuth.xyz:10058" + HEARTBEAT_INTERVAL = 300 # 5分钟(秒) + + # 创建并启动心跳线程 + heartbeat_thread = HeartbeatThread(SERVER_URL, HEARTBEAT_INTERVAL) + heartbeat_thread.start() + + return heartbeat_thread # 返回线程对象,便于外部控制 \ No newline at end of file