优化FastHosts,增加Spend(耗时)

This commit is contained in:
injoyai
2025-06-18 13:50:23 +08:00
parent 34701c4197
commit 12079f1ee2
2 changed files with 21 additions and 6 deletions

View File

@@ -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))
}

View File

@@ -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
}