// latency_probe.dart — 客户端实测节点延迟。 // // per-client 到节点的 RTT 服务端无法代知(agent 到控制面的 RTT ≠ 用户 ping), // 故由客户端对各节点入口做并行 TCP 握手计时,得到真实 per-client 延迟。 // 取多次取最小(规避抖动),失败返回 0(UI 显示 — )。 import 'dart:async'; import 'dart:io'; /// 对 [host]:[port] 做 [samples] 次 TCP 握手,返回最小耗时(ms);全失败返回 0。 Future probeLatency( String host, int port, { int samples = 2, Duration timeout = const Duration(seconds: 3), }) async { if (host.isEmpty || port <= 0) return 0; int best = 0; for (var i = 0; i < samples; i++) { final sw = Stopwatch()..start(); try { final socket = await Socket.connect(host, port, timeout: timeout); sw.stop(); socket.destroy(); final ms = sw.elapsedMilliseconds; if (best == 0 || ms < best) best = ms; } catch (_) { // 单次失败忽略,继续下一次采样。 } } return best; } /// 并行测一组 (uuid, host, port),返回 uuid→延迟(ms)。 Future> probeAll( Iterable<({String uuid, String host, int port})> targets, ) async { final entries = await Future.wait(targets.map((tg) async { final ms = await probeLatency(tg.host, tg.port); return MapEntry(tg.uuid, ms); })); return Map.fromEntries(entries); }