Update SpeedtestService.cs

This commit is contained in:
2dust 2025-11-24 18:57:08 +08:00
parent 9137bd0924
commit 88a377ea9f

View file

@ -323,30 +323,28 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
{ {
var responseTime = -1; var responseTime = -1;
if (!IPAddress.TryParse(url, out var ipAddress))
{
var ipHostInfo = await Dns.GetHostEntryAsync(url);
ipAddress = ipHostInfo.AddressList.First();
}
IPEndPoint endPoint = new(ipAddress, port);
using Socket clientSocket = new(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
var timer = Stopwatch.StartNew();
try try
{ {
if (!IPAddress.TryParse(url, out var ipAddress))
{
var ipHostInfo = await Dns.GetHostEntryAsync(url);
ipAddress = ipHostInfo.AddressList.First();
}
IPEndPoint endPoint = new(ipAddress, port);
using Socket clientSocket = new(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
var timer = Stopwatch.StartNew();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await clientSocket.ConnectAsync(endPoint, cts.Token).ConfigureAwait(false); await clientSocket.ConnectAsync(endPoint, cts.Token).ConfigureAwait(false);
timer.Stop();
responseTime = (int)timer.Elapsed.TotalMilliseconds;
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
// 超时情况responseTime保持为-1
} }
catch (Exception ex) finally
{ {
Logging.SaveLog(_tag, ex); timer.Stop();
responseTime = (int)timer.Elapsed.TotalMilliseconds;
} }
return responseTime; return responseTime;
} }