import 'dart:async'; import 'dart:io'; import '../models/models.dart'; /// 网络检测服务 class NetworkService { static final NetworkService _instance = NetworkService._internal(); factory NetworkService() => _instance; NetworkService._internal(); /// Ping指定主机 Future ping(String host, {int timeout = 5000}) async { try { final stopwatch = Stopwatch()..start(); // 尝试建立TCP连接来检测 final socket = await Socket.connect( host, 80, timeout: Duration(milliseconds: timeout), ); stopwatch.stop(); socket.destroy(); return stopwatch.elapsedMilliseconds; } catch (e) { return null; } } /// 检测设备是否在线 Future checkDevice(DeviceStatus device) async { final stopwatch = Stopwatch()..start(); try { final socket = await Socket.connect( device.ip, device.port, timeout: const Duration(seconds: 5), ); stopwatch.stop(); socket.destroy(); return device.copyWith( state: DeviceState.online, latency: stopwatch.elapsedMilliseconds, lastCheck: DateTime.now(), errorMessage: null, ); } on SocketException catch (e) { return device.copyWith( state: DeviceState.offline, latency: null, lastCheck: DateTime.now(), errorMessage: e.message, ); } catch (e) { return device.copyWith( state: DeviceState.unknown, latency: null, lastCheck: DateTime.now(), errorMessage: e.toString(), ); } } /// 批量检测设备 Future> checkAllDevices(List devices) async { final results = await Future.wait( devices.map((device) => checkDevice(device)), ); return results; } /// 检测网络连通性(通过多个公共DNS) Future checkInternetConnection() async { final hosts = [ '8.8.8.8', // Google DNS '114.114.114.114', // 114 DNS '223.5.5.5', // 阿里 DNS ]; for (final host in hosts) { final latency = await ping(host); if (latency != null) { return true; } } return false; } /// 获取本地IP地址 Future getLocalIp() async { try { final interfaces = await NetworkInterface.list( type: InternetAddressType.IPv4, ); for (final interface in interfaces) { for (final addr in interface.addresses) { if (!addr.isLoopback) { return addr.address; } } } } catch (e) { // 忽略错误 } return '未知'; } /// 测量到指定主机的延迟 Future measureLatency(String host) async { final latency = await ping(host); return latency ?? -1; } }