measureWebsocketLatency function
Measure WebSocket connection latency to a given URL
Returns the latency in milliseconds, or double.infinity if the connection fails or times out (after 1000ms).
Implementation
Future<double> measureWebsocketLatency(String wsUrl) async {
final stopwatch = Stopwatch()..start();
try {
final uri = Uri.parse(wsUrl);
final httpUrl = uri.replace(scheme: uri.scheme == 'wss' ? 'https' : 'http');
// Try HTTP ping as a proxy for WebSocket latency
final response = await http
.get(httpUrl)
.timeout(const Duration(milliseconds: 5000))
.catchError((_) => http.Response('', 500));
stopwatch.stop();
return response.statusCode < 500
? stopwatch.elapsedMilliseconds.toDouble()
: double.infinity;
} catch (_) {
return double.infinity;
}
}