From 12079f1ee21a3fe1c73a2c19e20485af359ea333 Mon Sep 17 00:00:00 2001 From: injoyai <1113655791@qq.com> Date: Wed, 18 Jun 2025 13:50:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96FastHosts,=E5=A2=9E=E5=8A=A0S?= =?UTF-8?q?pend(=E8=80=97=E6=97=B6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- example/FastHosts/main.go | 2 +- hosts.go | 25 ++++++++++++++++++++----- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/example/FastHosts/main.go b/example/FastHosts/main.go index f2a6f40..fa35717 100644 --- a/example/FastHosts/main.go +++ b/example/FastHosts/main.go @@ -8,7 +8,7 @@ import ( func main() { ls := tdx.FastHosts(tdx.Hosts...) for _, v := range ls { - logs.Debug(v) + logs.Debug(v.Host, v.Spend) } logs.Debug("总数量:", len(ls)) } diff --git a/hosts.go b/hosts.go index 018de93..9d828e2 100644 --- a/hosts.go +++ b/hosts.go @@ -1,10 +1,12 @@ package tdx import ( + "github.com/injoyai/base/types" "github.com/injoyai/logs" "net" "strings" "sync" + "time" ) var ( @@ -76,11 +78,11 @@ var ( ) // FastHosts 通过tcp(ping不可用)的方式筛选可用的地址,并排序(有点误差) -func FastHosts(hosts ...string) []string { +func FastHosts(hosts ...string) []DialResult { wg := sync.WaitGroup{} wg.Add(len(hosts)) mu := sync.Mutex{} - ls := []string(nil) + ls := types.List[DialResult](nil) for _, host := range hosts { go func(host string) { defer wg.Done() @@ -88,17 +90,30 @@ func FastHosts(hosts ...string) []string { if !strings.Contains(addr, ":") { addr += ":7709" } + now := time.Now() c, err := net.Dial("tcp", addr) if err != nil { logs.Err(err) return } - defer c.Close() + spend := time.Since(now) + c.Close() mu.Lock() - ls = append(ls, host) + ls = append(ls, DialResult{ + Host: host, + Spend: spend, + }) mu.Unlock() }(host) } wg.Wait() - return ls + return ls.Sort(func(a, b DialResult) bool { + return a.Spend < b.Spend + }) +} + +// DialResult 连接结果 +type DialResult struct { + Host string + Spend time.Duration }