Skip to content

Commit

Permalink
improve:add error handling in SetReadDeadline and SetWriteDeadline an…
Browse files Browse the repository at this point in the history
…d simplify the maxReconnectInterval calculation
  • Loading branch information
No-SilverBullet committed Jul 4, 2024
1 parent 5bd3869 commit 3f88499
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
15 changes: 8 additions & 7 deletions transport/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"crypto/x509"
"encoding/pem"
"fmt"
"math"
"net"
"os"
"strings"
Expand Down Expand Up @@ -208,14 +209,18 @@ func (c *client) dialUDP() Session {
}

// check connection alive by write/read action
conn.SetWriteDeadline(time.Now().Add(1e9))
if err := conn.SetWriteDeadline(time.Now().Add(1e9)); err != nil {
log.Warnf("failed to set write deadline: %+v", err)
}
if length, err = conn.Write(connectPingPackage[:]); err != nil {
conn.Close()
log.Warnf("conn.Write(%s) = {length:%d, err:%+v}", string(connectPingPackage), length, perrors.WithStack(err))
<-gxtime.After(connectInterval)
continue
}
conn.SetReadDeadline(time.Now().Add(1e9))
if err := conn.SetReadDeadline(time.Now().Add(1e9)); err != nil {
log.Warnf("failed to set read deadline: %+v", err)
}
length, err = conn.Read(buf)
if netErr, ok := perrors.Cause(err).(net.Error); ok && netErr.Timeout() {
err = nil
Expand Down Expand Up @@ -449,11 +454,7 @@ func (c *client) reConnect() {
}
c.connect()
reconnectAttempts++
if reconnectAttempts > maxBackOffTimes {
maxReconnectInterval = int64(maxBackOffTimes) * int64(reconnectInterval)
} else {
maxReconnectInterval = int64(reconnectAttempts) * int64(reconnectInterval)
}
maxReconnectInterval = int64(math.Min(float64(reconnectAttempts), float64(maxBackOffTimes))) * int64(reconnectInterval)
<-gxtime.After(time.Duration(maxReconnectInterval))
}
}
Expand Down
8 changes: 6 additions & 2 deletions transport/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -860,8 +860,12 @@ func (s *session) stop() {
// let read/Write timeout asap
now := time.Now()
if conn := s.Conn(); conn != nil {
conn.SetReadDeadline(now.Add(s.ReadTimeout()))
conn.SetWriteDeadline(now.Add(s.WriteTimeout()))
if err := conn.SetReadDeadline(now.Add(s.ReadTimeout())); err != nil {
log.Warnf("failed to set read deadline: %+v", err)
}
if err := conn.SetWriteDeadline(now.Add(s.WriteTimeout())); err != nil {
log.Warnf("failed to set write deadline: %+v", err)
}
}
close(s.done)
clt, cltFound := s.GetAttribute(sessionClientKey).(*client)
Expand Down

0 comments on commit 3f88499

Please sign in to comment.