Refactoring GetRealPingTime

pull/7789/head
2dust 2025-08-17 20:51:49 +08:00
parent f66226c103
commit 7b7fe0ef46
4 changed files with 72 additions and 67 deletions

View File

@ -1,17 +1,20 @@
using System.Net;
namespace ServiceLib.Handler; namespace ServiceLib.Handler;
public static class ConnectionHandler public static class ConnectionHandler
{ {
private static readonly string _tag = "ConnectionHandler";
public static async Task<string> RunAvailabilityCheck() public static async Task<string> RunAvailabilityCheck()
{ {
var downloadHandle = new DownloadService(); var time = await GetRealPingTime();
var time = await downloadHandle.RunAvailabilityCheck(null); var ip = time > 0 ? await GetIPInfo() ?? Global.None : Global.None;
var ip = time > 0 ? await GetIPInfo(downloadHandle) ?? Global.None : Global.None;
return string.Format(ResUI.TestMeOutput, time, ip); return string.Format(ResUI.TestMeOutput, time, ip);
} }
private static async Task<string?> GetIPInfo(DownloadService downloadHandle) private static async Task<string?> GetIPInfo()
{ {
var url = AppManager.Instance.Config.SpeedTestItem.IPAPIUrl; var url = AppManager.Instance.Config.SpeedTestItem.IPAPIUrl;
if (url.IsNullOrEmpty()) if (url.IsNullOrEmpty())
@ -19,6 +22,7 @@ public static class ConnectionHandler
return null; return null;
} }
var downloadHandle = new DownloadService();
var result = await downloadHandle.TryDownloadString(url, true, ""); var result = await downloadHandle.TryDownloadString(url, true, "");
if (result == null) if (result == null)
{ {
@ -36,4 +40,31 @@ public static class ConnectionHandler
return $"({country ?? "unknown"}) {ip}"; return $"({country ?? "unknown"}) {ip}";
} }
private static async Task<int> GetRealPingTime()
{
var responseTime = -1;
try
{
var port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks);
var webProxy = new WebProxy($"socks5://{Global.Loopback}:{port}");
var url = AppManager.Instance.Config.SpeedTestItem.SpeedPingTestUrl;
for (var i = 0; i < 2; i++)
{
responseTime = await HttpClientHelper.Instance.GetRealPingTime(url, webProxy, 10);
if (responseTime > 0)
{
break;
}
await Task.Delay(500);
}
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
return -1;
}
return responseTime;
}
} }

View File

@ -1,3 +1,5 @@
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Net.Mime; using System.Net.Mime;
using System.Text; using System.Text;
@ -202,4 +204,35 @@ public class HttpClientHelper
} }
} while (isMoreToRead); } while (isMoreToRead);
} }
public async Task<int> GetRealPingTime(string url, IWebProxy? webProxy, int downloadTimeout)
{
var responseTime = -1;
try
{
using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(downloadTimeout));
using var client = new HttpClient(new SocketsHttpHandler()
{
Proxy = webProxy,
UseProxy = webProxy != null
});
List<int> oneTime = new();
for (var i = 0; i < 2; i++)
{
var timer = Stopwatch.StartNew();
await client.GetAsync(url, cts.Token).ConfigureAwait(false);
timer.Stop();
oneTime.Add((int)timer.Elapsed.TotalMilliseconds);
await Task.Delay(100);
}
responseTime = oneTime.Where(x => x > 0).OrderBy(x => x).FirstOrDefault();
}
catch //(Exception ex)
{
//Utile.SaveLog(ex.Message, ex);
}
return responseTime;
}
} }

View File

@ -210,63 +210,6 @@ public class DownloadService
return null; return null;
} }
public async Task<int> RunAvailabilityCheck(IWebProxy? webProxy)
{
var responseTime = -1;
try
{
webProxy ??= await GetWebProxy(true);
var config = AppManager.Instance.Config;
for (var i = 0; i < 2; i++)
{
responseTime = await GetRealPingTime(config.SpeedTestItem.SpeedPingTestUrl, webProxy, 10);
if (responseTime > 0)
{
break;
}
await Task.Delay(500);
}
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
return -1;
}
return responseTime;
}
public async Task<int> GetRealPingTime(string url, IWebProxy? webProxy, int downloadTimeout)
{
var responseTime = -1;
try
{
using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(downloadTimeout));
using var client = new HttpClient(new SocketsHttpHandler()
{
Proxy = webProxy,
UseProxy = webProxy != null
});
List<int> oneTime = new();
for (var i = 0; i < 2; i++)
{
var timer = Stopwatch.StartNew();
await client.GetAsync(url, cts.Token).ConfigureAwait(false);
timer.Stop();
oneTime.Add((int)timer.Elapsed.TotalMilliseconds);
await Task.Delay(100);
}
responseTime = oneTime.Where(x => x > 0).OrderBy(x => x).FirstOrDefault();
}
catch //(Exception ex)
{
//Utile.SaveLog(ex.Message, ex);
}
return responseTime;
}
private async Task<WebProxy?> GetWebProxy(bool blProxy) private async Task<WebProxy?> GetWebProxy(bool blProxy)
{ {
if (!blProxy) if (!blProxy)

View File

@ -198,8 +198,6 @@ public class SpeedtestService
} }
await Task.Delay(1000); await Task.Delay(1000);
var downloadHandle = new DownloadService();
List<Task> tasks = new(); List<Task> tasks = new();
foreach (var it in selecteds) foreach (var it in selecteds)
{ {
@ -213,7 +211,7 @@ public class SpeedtestService
} }
tasks.Add(Task.Run(async () => tasks.Add(Task.Run(async () =>
{ {
await DoRealPing(downloadHandle, it); await DoRealPing(it);
})); }));
} }
await Task.WhenAll(tasks); await Task.WhenAll(tasks);
@ -263,7 +261,7 @@ public class SpeedtestService
else else
{ {
await Task.Delay(1000); await Task.Delay(1000);
var delay = await DoRealPing(downloadHandle, it); var delay = await DoRealPing(it);
if (blSpeedTest) if (blSpeedTest)
{ {
if (delay > 0) if (delay > 0)
@ -294,10 +292,10 @@ public class SpeedtestService
await Task.WhenAll(tasks); await Task.WhenAll(tasks);
} }
private async Task<int> DoRealPing(DownloadService downloadHandle, ServerTestItem it) private async Task<int> DoRealPing(ServerTestItem it)
{ {
var webProxy = new WebProxy($"socks5://{Global.Loopback}:{it.Port}"); var webProxy = new WebProxy($"socks5://{Global.Loopback}:{it.Port}");
var responseTime = await downloadHandle.GetRealPingTime(_config.SpeedTestItem.SpeedPingTestUrl, webProxy, 10); var responseTime = await HttpClientHelper.Instance.GetRealPingTime(_config.SpeedTestItem.SpeedPingTestUrl, webProxy, 10);
ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime); ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime);
UpdateFunc(it.IndexId, responseTime.ToString()); UpdateFunc(it.IndexId, responseTime.ToString());