mirror of
https://github.com/injoyai/tdx.git
synced 2025-11-26 21:25:35 +08:00
优化FastHosts,增加Spend(耗时)
This commit is contained in:
@@ -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))
|
||||
}
|
||||
|
||||
25
hosts.go
25
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user