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() {
|
func main() {
|
||||||
ls := tdx.FastHosts(tdx.Hosts...)
|
ls := tdx.FastHosts(tdx.Hosts...)
|
||||||
for _, v := range ls {
|
for _, v := range ls {
|
||||||
logs.Debug(v)
|
logs.Debug(v.Host, v.Spend)
|
||||||
}
|
}
|
||||||
logs.Debug("总数量:", len(ls))
|
logs.Debug("总数量:", len(ls))
|
||||||
}
|
}
|
||||||
|
|||||||
25
hosts.go
25
hosts.go
@@ -1,10 +1,12 @@
|
|||||||
package tdx
|
package tdx
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/injoyai/base/types"
|
||||||
"github.com/injoyai/logs"
|
"github.com/injoyai/logs"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -76,11 +78,11 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// FastHosts 通过tcp(ping不可用)的方式筛选可用的地址,并排序(有点误差)
|
// FastHosts 通过tcp(ping不可用)的方式筛选可用的地址,并排序(有点误差)
|
||||||
func FastHosts(hosts ...string) []string {
|
func FastHosts(hosts ...string) []DialResult {
|
||||||
wg := sync.WaitGroup{}
|
wg := sync.WaitGroup{}
|
||||||
wg.Add(len(hosts))
|
wg.Add(len(hosts))
|
||||||
mu := sync.Mutex{}
|
mu := sync.Mutex{}
|
||||||
ls := []string(nil)
|
ls := types.List[DialResult](nil)
|
||||||
for _, host := range hosts {
|
for _, host := range hosts {
|
||||||
go func(host string) {
|
go func(host string) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
@@ -88,17 +90,30 @@ func FastHosts(hosts ...string) []string {
|
|||||||
if !strings.Contains(addr, ":") {
|
if !strings.Contains(addr, ":") {
|
||||||
addr += ":7709"
|
addr += ":7709"
|
||||||
}
|
}
|
||||||
|
now := time.Now()
|
||||||
c, err := net.Dial("tcp", addr)
|
c, err := net.Dial("tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logs.Err(err)
|
logs.Err(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer c.Close()
|
spend := time.Since(now)
|
||||||
|
c.Close()
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
ls = append(ls, host)
|
ls = append(ls, DialResult{
|
||||||
|
Host: host,
|
||||||
|
Spend: spend,
|
||||||
|
})
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
}(host)
|
}(host)
|
||||||
}
|
}
|
||||||
wg.Wait()
|
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