forked from rancher/dynamiclistener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp.go
38 lines (32 loc) · 699 Bytes
/
tcp.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
package dynamiclistener
import (
"fmt"
"net"
"reflect"
"time"
)
func NewTCPListener(ip string, port int) (net.Listener, error) {
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", ip, port))
if err != nil {
return nil, err
}
tcpListener, ok := l.(*net.TCPListener)
if !ok {
return nil, fmt.Errorf("wrong listener type: %v", reflect.TypeOf(tcpListener))
}
return tcpKeepAliveListener{
TCPListener: tcpListener,
}, nil
}
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}