改进获取随机端口算法

This commit is contained in:
刘祥超
2020-12-03 11:23:29 +08:00
parent 15bd634280
commit bac7bb61df
2 changed files with 22 additions and 1 deletions

View File

@@ -3,6 +3,7 @@ package nodeconfigs
import (
"fmt"
"github.com/iwind/TeaGo/rands"
"net"
)
// 默认的TOA配置
@@ -68,7 +69,12 @@ func (this *TOAConfig) SockFile() string {
// 获取随机端口
func (this *TOAConfig) RandLocalPort() uint16 {
return uint16(rands.Int(this.minLocalPort, this.maxLocalPort))
listener, err := net.Listen("tcp", ":0")
if err != nil {
return uint16(rands.Int(this.minLocalPort, this.maxLocalPort))
}
_ = listener.Close()
return uint16(listener.Addr().(*net.TCPAddr).Port)
}
// 转换为参数的形式

View File

@@ -1,8 +1,10 @@
package nodeconfigs
import (
"net"
"runtime"
"testing"
"time"
)
func TestTOAConfig_RandLocalPort(t *testing.T) {
@@ -27,6 +29,19 @@ func TestTOAConfig_RandLocalPort(t *testing.T) {
}
}
func TestTOAConfig_FreePort(t *testing.T) {
before := time.Now()
listener, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
t.Log(listener.Addr())
_ = listener.Close()
t.Log(time.Since(before).Seconds()*1000, "ms")
time.Sleep(30 * time.Second)
}
func TestTOAConfig_AsArgs(t *testing.T) {
toa := &TOAConfig{
IsOn: false,