checkNetworkHealth method

Future<NetworkStatus> checkNetworkHealth({
  1. int slowThresholdMs = 3000,
  2. int timeoutMs = 10000,
})

检查网络是否可访问,并以最快成功请求的响应时间判定健康状态。

slowThresholdMs 为判定网络较慢的阈值;timeoutMs 为单个请求超时。

Implementation

Future<NetworkStatus> checkNetworkHealth({
  int slowThresholdMs = 3000,
  int timeoutMs = 10000,
}) async {
  final urls = [..._testUrls, ...extraUrls];
  if (urls.isEmpty) return NetworkStatus.unavailable;

  final responseTimes = <int>[];
  final client = Dio();
  final requests = urls.map((url) async {
    final stopwatch = Stopwatch()..start();
    try {
      final response = await client.get(
        url,
        options: Options(
          receiveTimeout: Duration(milliseconds: timeoutMs),
          sendTimeout: Duration(milliseconds: timeoutMs),
        ),
      );
      if (response.statusCode == 200) {
        responseTimes.add(stopwatch.elapsedMilliseconds);
      }
    } catch (error) {
      Logger.log('网络健康检测失败: $url, 错误: $error');
    } finally {
      stopwatch.stop();
    }
  });

  await Future.wait(requests);
  if (responseTimes.isEmpty) return NetworkStatus.unavailable;

  fastResponseTime = responseTimes.reduce(min);
  return fastResponseTime <= slowThresholdMs
      ? NetworkStatus.available
      : NetworkStatus.slow;
}