From 316803bc8eface750ad29badb94187c88107e3cf Mon Sep 17 00:00:00 2001 From: chenqinghe Date: Tue, 18 Oct 2022 16:58:10 +0800 Subject: [PATCH] feat: reconnect set timeout --- client.go | 18 +++++++++++++++++- example/client/client.go | 2 +- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/client.go b/client.go index 89d49be..eb6acf2 100644 --- a/client.go +++ b/client.go @@ -70,6 +70,22 @@ func (cli *Client) Dial(network string, addr string) (*Session, error) { return cli.mgr.StoreConn(conn) } +func (cli *Client) DialTimeout(network string, addr string, timeout time.Duration) (*Session, error) { + c, err := net.DialTimeout(network, addr, timeout) + if err != nil { + return nil, err + } + + conn := newConn(c, cli.codec) + if cli.opts.OnConnected != nil { + if err := cli.opts.OnConnected(conn); err != nil { + return nil, err + } + } + + return cli.mgr.StoreConn(conn) +} + type ReconnectPolicy interface { Retry() bool Timer() *time.Timer @@ -82,7 +98,7 @@ func (cli *Client) reconnect(sess *Session) { for cli.needReconnect(sess) && policy.Retry() { logrus.WithField("sessionId", sess.id).WithField("remoteAddr", sess.RemoteAddr().String()).Debugln("session reconnect") - if s, err := cli.Dial(addr.Network(), addr.String()); err == nil { + if s, err := cli.DialTimeout(addr.Network(), addr.String(), time.Second*5); err == nil { s.data = sess.data s.user = sess.user s.lastPackTs = sess.lastPackTs diff --git a/example/client/client.go b/example/client/client.go index 180b4b3..2099f64 100644 --- a/example/client/client.go +++ b/example/client/client.go @@ -41,7 +41,7 @@ func main() { Version: 0x01, ID: 1, Timestamp: time.Now().Unix(), - Length: uint32(len(data)), + Length: uint64(len(data)), }, Data: data, })