From 65df583f0c7407df22fd722052f9815eed516456 Mon Sep 17 00:00:00 2001 From: Bruce Wayne Date: Sat, 25 Apr 2020 12:27:07 +0800 Subject: [PATCH] Refine TCPing --- Netch/Models/Server.cs | 25 +++---------------------- Netch/Utils/Utils.cs | 26 +++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/Netch/Models/Server.cs b/Netch/Models/Server.cs index b60deb88..9bef4847 100644 --- a/Netch/Models/Server.cs +++ b/Netch/Models/Server.cs @@ -1,7 +1,4 @@ using System; -using System.Diagnostics; -using System.Net; -using System.Net.Sockets; using System.Threading.Tasks; namespace Netch.Models @@ -181,27 +178,11 @@ namespace Netch.Models var list = new Task[3]; for (var i = 0; i < 3; i++) { - list[i] = Task.Run(() => + list[i] = Task.Run(async () => { try { - using (var client = new Socket(SocketType.Stream, ProtocolType.Tcp)) - { - var watch = new Stopwatch(); - watch.Start(); - - var task = client.BeginConnect(new IPEndPoint(destination, Port), result => - { - watch.Stop(); - }, 0); - - if (task.AsyncWaitHandle.WaitOne(1000)) - { - return (int)watch.ElapsedMilliseconds; - } - - return 1000; - } + return await Utils.Utils.TCPingAsync(destination, Port); } catch (Exception) { @@ -210,7 +191,7 @@ namespace Netch.Models }); } - Task.WaitAll(list); + Task.WaitAll(list[0], list[1], list[2]); var min = Math.Min(list[0].Result, list[1].Result); min = Math.Min(min, list[2].Result); diff --git a/Netch/Utils/Utils.cs b/Netch/Utils/Utils.cs index f4bb0d65..efe0f693 100644 --- a/Netch/Utils/Utils.cs +++ b/Netch/Utils/Utils.cs @@ -1,5 +1,10 @@ -using System.Diagnostics; +using System; +using System.Diagnostics; using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; namespace Netch.Utils { @@ -40,5 +45,24 @@ namespace Netch.Utils return false; } + + public static async Task TCPingAsync(IPAddress ip, int port, int timeout = 1000, CancellationToken ct = default) + { + using var client = new TcpClient(ip.AddressFamily); + var task = client.ConnectAsync(ip, port); + + var stopwatch = new Stopwatch(); + stopwatch.Start(); + + var resTask = await Task.WhenAny(Task.Delay(timeout, ct), task); + + stopwatch.Stop(); + if (resTask == task && client.Connected) + { + var t = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds); + return t; + } + return timeout; + } } }