# -*- coding: utf-8 -*- """真机测试:被控端复用连接之后,长轮询的成功率提升了多少? 对照: 改之前(每次新建连接):约 70% 改之后(复用连接) :期望接近 100% 做法: 起一个真的 RelayLink,连公网中转 https://relay.xxmxxs.top, 连续轮询 60 次,统计成功/失败。 """ from __future__ import annotations import sys import tempfile import threading import time from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "windows")) from lanremote.config import Store # noqa: E402 from lanremote.relay import RelayLink # noqa: E402 RELAY = "https://relay.xxmxxs.top" ROUNDS = 60 def main() -> int: work = Path(tempfile.mkdtemp(prefix="keepalive_")) store = Store(work) store.set("relay_url", RELAY) store.set("pairing_code", "%06d" % __import__("random").randint(1, 999999)) store.set("device_name", "keepalive-probe") logs = [] link = RelayLink(store, log=logs.append) # 先把地址和候选解析好 link.candidates = [RELAY] link.url = RELAY # deviceId 走正常的生成逻辑(带机器名 + 随机后缀) link.device_id = link._ensure_device_id() print(f" 目标中转: {RELAY}") print(" 先登记…") ok_register = False for attempt in range(3): try: link._register() ok_register = True break except Exception as exc: # noqa: BLE001 print(f" 第 {attempt + 1} 次登记失败: {type(exc).__name__}: {exc}") time.sleep(1.5) if not ok_register: print(" 登记不上,测试没法继续") return 1 print(f" 登记成功,配对码 {link.code}") print() print(f" 连续轮询 {ROUNDS} 次(复用同一条连接)…") good = 0 bad = 0 times = [] first_failure = None for index in range(ROUNDS): started = time.time() try: link._poll_once() good += 1 times.append((time.time() - started) * 1000) except Exception as exc: # noqa: BLE001 bad += 1 if first_failure is None: first_failure = f"{type(exc).__name__}: {exc}" # 失败也让它重试(真实循环就是这么做的) if (index + 1) % 20 == 0: print(f" 已跑 {index + 1} 次:成功 {good},失败 {bad}") total = good + bad pct = good * 100 // total if total else 0 print() print("=" * 58) print(f" 成功 {good} / {total} = {pct}%") if times: times.sort() print(f" 单次耗时 中位 {times[len(times) // 2]:.0f}ms " f"最快 {times[0]:.0f}ms 最慢 {times[-1]:.0f}ms") if first_failure: print(f" 首次失败: {first_failure}") print() print(" 对照(实测):") print(" 每次新建连接(改之前): 约 70%") print(f" 复用连接(改之后) : {pct}%") print() if pct >= 95: print(" ✓ 达到目标(≥95%)") elif pct >= 85: print(" ~ 明显改善,但还没到 95%") else: print(" ✗ 没改善,得换个思路") # 清理 try: link.close() except Exception: # noqa: BLE001 pass return 0 if __name__ == "__main__": sys.exit(main())