Set keep-alive for tcp connections

This commit is contained in:
9seconds
2020-03-25 10:01:17 +03:00
parent 8977d77a13
commit 850bed0dfc
+11
View File
@@ -3,10 +3,13 @@ package utils
import (
"fmt"
"net"
"time"
"github.com/9seconds/mtg/config"
)
const tcpKeepAlivePingPeriod = 2 * time.Second
func InitTCP(conn net.Conn) error {
tcpConn := conn.(*net.TCPConn)
@@ -22,5 +25,13 @@ func InitTCP(conn net.Conn) error {
return fmt.Errorf("cannot set write buffer size: %w", err)
}
if err := tcpConn.SetKeepAlive(true); err != nil {
return fmt.Errorf("cannot enable keep-alive: %w", err)
}
if err := tcpConn.SetKeepAlivePeriod(tcpKeepAlivePingPeriod); err != nil {
return fmt.Errorf("cannot set keep-alive period: %w", err)
}
return nil
}