-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_acceptor.go
103 lines (87 loc) · 2.29 KB
/
tcp_acceptor.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package dnet
import (
"errors"
"io"
"net"
"strings"
"sync/atomic"
"time"
)
type TCPAcceptor struct {
address string
listener net.Listener
started int32
}
// NewTCPAcceptor returns a new instance of TCPAcceptor
func NewTCPAcceptor(address string) *TCPAcceptor {
return &TCPAcceptor{address: address}
}
// ServeTCP listen and serve tcp address with AcceptorHandler
func ServeTCP(address string, handler AcceptorHandler) error {
return NewTCPAcceptor(address).Serve(handler)
}
// ServeTCPFunc listen and serve tcp address with AcceptorHandlerFunc
func ServeTCPFunc(address string, handler AcceptorHandlerFunc) error {
return NewTCPAcceptor(address).ServeFunc(handler)
}
// Serve listens and serve in the specified addr
func (this *TCPAcceptor) Serve(handler AcceptorHandler) error {
if handler == nil {
return errors.New("dnet:Serve handler is nil. ")
}
if !atomic.CompareAndSwapInt32(&this.started, 0, 1) {
return errors.New("dnet:Serve acceptor is already started. ")
}
listener, err := net.Listen("tcp", this.address)
if err != nil {
return err
}
this.listener = listener
defer this.Stop()
var tempDelay time.Duration
for {
conn, err := this.listener.Accept()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
time.Sleep(tempDelay)
continue
}
if strings.Contains(err.Error(), "use of closed network connection") {
return io.EOF
}
return err
}
go handler.OnConnection(conn)
}
}
// ServeFunc listens and serve in the specified addr
func (this *TCPAcceptor) ServeFunc(handler AcceptorHandlerFunc) error {
return this.Serve(handler)
}
// Addr returns the addr the acceptor will listen on
func (this *TCPAcceptor) Addr() net.Addr {
return this.listener.Addr()
}
// Stop stops the acceptor
func (this *TCPAcceptor) Stop() {
if atomic.CompareAndSwapInt32(&this.started, 1, 0) {
_ = this.listener.Close()
}
}
// DialTCP
func DialTCP(address string, timeout time.Duration) (net.Conn, error) {
tcpAddr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, err
}
dialer := &net.Dialer{Timeout: timeout}
return dialer.Dial(tcpAddr.Network(), address)
}