-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtcpkeepalive.go
45 lines (39 loc) · 929 Bytes
/
tcpkeepalive.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package netutil
import (
"net"
"time"
)
const (
keepAlivePeriod = 3 * time.Minute
)
// TCPKeepAliveListener wraps *net.TCPListener.
type TCPKeepAliveListener struct {
*net.TCPListener
}
// Accept returns a TCP keep-alive enabled connection.
func (l TCPKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := l.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(keepAlivePeriod)
return tc, nil
}
// KeepAliveListener returns TCPKeepAliveListener if l is a
// *net.TCPListener. Otherwise, l is returned without change.
func KeepAliveListener(l net.Listener) net.Listener {
if tl, ok := l.(*net.TCPListener); ok {
return TCPKeepAliveListener{tl}
}
return l
}
// SetKeepAlive enables TCP keep-alive if c is a *net.TCPConn.
func SetKeepAlive(c net.Conn) {
tc, ok := c.(*net.TCPConn)
if !ok {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(keepAlivePeriod)
}