Skip to content
This repository has been archived by the owner on May 26, 2022. It is now read-only.

Commit

Permalink
enable TCP keepalives
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Feb 17, 2021
1 parent 65b7bd8 commit 33b59b8
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions tcp.go
Expand Up @@ -22,6 +22,28 @@ var DefaultConnectTimeout = 5 * time.Second

var log = logging.Logger("tcp-tpt")

const keepAlivePeriod = 30 * time.Second

type canKeepAlive interface {
SetKeepAlive(bool) error
SetKeepAlivePeriod(time.Duration) error
}

var _ canKeepAlive = &net.TCPConn{}

func tryKeepAlive(conn net.Conn, keepAlive bool) {
keepAliveConn, ok := conn.(canKeepAlive)
if !ok {
log.Errorf("Can't set TCP keepalives.")
}
if err := keepAliveConn.SetKeepAlive(keepAlive); err != nil {
log.Errorf("Failed to enable TCP keepalive: %s", err)
}
if err := keepAliveConn.SetKeepAlivePeriod(keepAlivePeriod); err != nil {
log.Errorf("Failed set keepalive period: %s", err)
}
}

// try to set linger on the connection, if possible.
func tryLinger(conn net.Conn, sec int) {
type canLinger interface {
Expand All @@ -44,6 +66,7 @@ func (ll *lingerListener) Accept() (manet.Conn, error) {
return nil, err
}
tryLinger(c, ll.sec)
tryKeepAlive(c, true)
return c, nil
}

Expand Down Expand Up @@ -106,6 +129,7 @@ func (t *TcpTransport) Dial(ctx context.Context, raddr ma.Multiaddr, p peer.ID)
// linger is 0, connections are _reset_ instead of closed with a FIN.
// This means we can immediately reuse the 5-tuple and reconnect.
tryLinger(conn, 0)
tryKeepAlive(conn, true)
return t.Upgrader.UpgradeOutbound(ctx, t, conn, p)
}

Expand Down

0 comments on commit 33b59b8

Please sign in to comment.