forked from ejoy/goscon
-
Notifications
You must be signed in to change notification settings - Fork 3
/
tcp.go
58 lines (47 loc) · 1.1 KB
/
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"net"
"time"
"github.com/xjdrew/glog"
)
type tcpConn struct {
*net.TCPConn
readTimeout time.Duration
}
func (conn tcpConn) Read(b []byte) (int, error) {
if conn.readTimeout > 0 {
conn.SetReadDeadline(time.Now().Add(conn.readTimeout))
}
return conn.TCPConn.Read(b)
}
// TCPListener .
type TCPListener struct {
net.Listener
}
// Accept .
func (l *TCPListener) Accept() (conn net.Conn, err error) {
c, err := l.Listener.Accept()
if err != nil {
return
}
if glog.V(1) {
glog.Infof("accept new tcp connection: addr=%s", c.RemoteAddr())
}
keepalive := configItemBool("tcp_option.keepalive")
keepaliveInterval := configItemTime("tcp_option.keepalive_interval")
readTimeout := configItemTime("tcp_option.read_timeout")
t := c.(*net.TCPConn)
t.SetKeepAlive(keepalive)
t.SetKeepAlivePeriod(keepaliveInterval)
// t.SetLinger(0)
conn = tcpConn{t, readTimeout}
return
}
// NewTCPListener creates a new TCPListener
func NewTCPListener(laddr string) (*TCPListener, error) {
ln, err := net.Listen("tcp", laddr)
if err != nil {
return nil, err
}
return &TCPListener{ln}, nil
}