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 16, 2021
1 parent 65b7bd8 commit b7c7941
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions tcp.go
Expand Up @@ -33,6 +33,20 @@ func tryLinger(conn net.Conn, sec int) {
}
}

func tryKeepAlive(conn net.Conn, keepAlive bool) {
type canKeepAlive interface {
SetKeepAlive(bool) error
}

var _ canKeepAlive = &net.TCPConn{}

if keepALiveConn, ok := conn.(canKeepAlive); ok {
if err := keepALiveConn.SetKeepAlive(keepAlive); err != nil {
log.Warnf("Failed to enable TCP keepalive: %s", err)
}
}
}

type lingerListener struct {
manet.Listener
sec int
Expand All @@ -44,6 +58,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 +121,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 b7c7941

Please sign in to comment.