diff --git a/client.go b/client.go index b3cae5e..e88d78f 100644 --- a/client.go +++ b/client.go @@ -7,7 +7,7 @@ import ( "github.com/injoyai/conv" "github.com/injoyai/ios" "github.com/injoyai/ios/client" - "github.com/injoyai/ios/client/dial" + "github.com/injoyai/ios/module/tcp" "github.com/injoyai/logs" "github.com/injoyai/tdx/protocol" "runtime/debug" @@ -35,13 +35,18 @@ func Dial(addr string, op ...client.Option) (cli *Client, err error) { if !strings.Contains(addr, ":") { addr += ":7709" } + return DialWith(tcp.NewDial(addr), op...) +} + +// DialWith 与服务器建立连接 +func DialWith(dial ios.DialFunc, op ...client.Option) (cli *Client, err error) { cli = &Client{ Wait: wait.New(time.Second * 2), m: maps.NewSafe(), } - cli.Client, err = dial.TCP(addr, func(c *client.Client) { + cli.Client, err = client.Dial(dial, func(c *client.Client) { c.Logger.Debug(false) //关闭日志打印 c.Logger.WithHEX() //以HEX显示 c.SetOption(op...) //自定义选项 diff --git a/dial.go b/dial.go new file mode 100644 index 0000000..2c5e712 --- /dev/null +++ b/dial.go @@ -0,0 +1,29 @@ +package tdx + +import ( + "context" + "github.com/injoyai/ios" + "net" + "strings" + "time" +) + +func NewHostDial(hosts []string, timeout time.Duration) ios.DialFunc { + if len(hosts) == 0 { + hosts = Hosts + } + index := 0 + + return func(ctx context.Context) (ios.ReadWriteCloser, string, error) { + defer func() { index++ }() + if index >= len(hosts) { + index = 0 + } + addr := hosts[index] + if !strings.Contains(addr, ":") { + addr += ":7709" + } + c, err := net.DialTimeout("tcp", addr, timeout) + return c, hosts[index], err + } +} diff --git a/example/common/common.go b/example/common/common.go index a9e13c7..30651fa 100644 --- a/example/common/common.go +++ b/example/common/common.go @@ -6,14 +6,22 @@ import ( ) func Test(f func(c *tdx.Client)) { - for _, v := range tdx.Hosts { - c, err := tdx.Dial(v, tdx.WithDebug()) - if err != nil { - logs.PrintErr(err) - continue - } - f(c) - <-c.Done() - break - } + + //重连方式1,优点,同一个客户端指针 + c, err := tdx.DialWith(tdx.NewHostDial(tdx.Hosts, 0), tdx.WithDebug()) + logs.PanicErr(err) + f(c) + <-c.Done() + + //重连方式2 + //for _, v := range tdx.Hosts { + // c, err := tdx.DialWith(v, tdx.WithDebug()) + // if err != nil { + // logs.PrintErr(err) + // continue + // } + // f(c) + // <-c.Done() + // break + //} }