mirror of
https://github.com/netchx/netch.git
synced 2026-03-18 18:13:21 +08:00
Refine TCPing
This commit is contained in:
@@ -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<int>[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);
|
||||
|
||||
@@ -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<int> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user