forked from wuyingsong/tcp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_conn.go
219 lines (190 loc) · 4.01 KB
/
tcp_conn.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package tcp
import (
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"sync/atomic"
"time"
)
var (
ErrConnClosing = errors.New("use of closed network connection")
ErrBufferFull = errors.New("the async send buffer is full")
ErrWriteTimeout = errors.New("async write packet timeout")
)
type TCPConn struct {
callback CallBack
protocol Protocol
conn *net.TCPConn
readChan chan Packet
writeChan chan Packet
readDeadline time.Duration
writeDeadline time.Duration
exitChan chan struct{}
closeOnce sync.Once
exitFlag int32
extraData map[string]interface{}
}
func NewTCPConn(conn *net.TCPConn, callback CallBack, protocol Protocol) *TCPConn {
c := &TCPConn{
conn: conn,
callback: callback,
protocol: protocol,
readChan: make(chan Packet, readChanSize),
writeChan: make(chan Packet, writeChanSize),
exitChan: make(chan struct{}),
exitFlag: 0,
}
return c
}
func (c *TCPConn) Serve() error {
defer func() {
if r := recover(); r != nil {
logger.Println("tcp conn(%v) Serve error, %v ", c.GetRemoteIPAddress(), r)
}
}()
if c.callback == nil || c.protocol == nil {
err := fmt.Errorf("callback and protocol are not allowed to be nil")
c.Close()
return err
}
atomic.StoreInt32(&c.exitFlag, 1)
c.callback.OnConnected(c)
go c.readLoop()
go c.writeLoop()
go c.handleLoop()
return nil
}
func (c *TCPConn) readLoop() {
defer func() {
recover()
c.Close()
}()
for {
select {
case <-c.exitChan:
return
default:
if c.readDeadline > 0 {
c.conn.SetReadDeadline(time.Now().Add(c.readDeadline))
}
p, err := c.protocol.ReadPacket(c.conn)
if err != nil {
if err != io.EOF {
c.callback.OnError(err)
}
return
}
c.readChan <- p
}
}
}
func (c *TCPConn) ReadPacket() (Packet, error) {
if c.protocol == nil {
return nil, errors.New("no protocol impl")
}
return c.protocol.ReadPacket(c.conn)
}
func (c *TCPConn) writeLoop() {
defer func() {
recover()
c.Close()
}()
for pkt := range c.writeChan {
if pkt == nil {
continue
}
if c.writeDeadline > 0 {
c.conn.SetWriteDeadline(time.Now().Add(c.writeDeadline))
}
if err := c.protocol.WritePacket(c.conn, pkt); err != nil {
c.callback.OnError(err)
return
}
}
}
func (c *TCPConn) handleLoop() {
defer func() {
recover()
c.Close()
}()
for p := range c.readChan {
if p == nil {
continue
}
c.callback.OnMessage(c, p)
}
}
func (c *TCPConn) AsyncWritePacket(p Packet) error {
if c.IsClosed() {
return ErrConnClosing
}
select {
case c.writeChan <- p:
return nil
default:
return ErrBufferFull
}
}
func (c *TCPConn) AsyncWritePacketWithTimeout(p Packet, sec int) error {
if c.IsClosed() {
return ErrConnClosing
}
select {
case c.writeChan <- p:
return nil
case <-time.After(time.Second * time.Duration(sec)):
return ErrWriteTimeout
}
}
func (c *TCPConn) Close() {
c.closeOnce.Do(func() {
atomic.StoreInt32(&c.exitFlag, 0)
close(c.exitChan)
close(c.writeChan)
close(c.readChan)
if c.callback != nil {
c.callback.OnDisconnected(c)
}
c.conn.Close()
})
}
func (c *TCPConn) GetRawConn() *net.TCPConn {
return c.conn
}
func (c *TCPConn) IsClosed() bool {
return atomic.LoadInt32(&c.exitFlag) == 0
}
func (c *TCPConn) GetLocalAddr() net.Addr {
return c.conn.LocalAddr()
}
//LocalIPAddress 返回socket连接本地的ip地址
func (c *TCPConn) GetLocalIPAddress() string {
return strings.Split(c.GetLocalAddr().String(), ":")[0]
}
func (c *TCPConn) GetRemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
func (c *TCPConn) GetRemoteIPAddress() string {
return strings.Split(c.GetRemoteAddr().String(), ":")[0]
}
func (c *TCPConn) setReadDeadline(t time.Duration) {
c.readDeadline = t
}
func (c *TCPConn) setWriteDeadline(t time.Duration) {
c.writeDeadline = t
}
func (c *TCPConn) SetExtraData(key string, data interface{}) {
if c.extraData == nil {
c.extraData = make(map[string]interface{})
}
c.extraData[key] = data
}
func (c *TCPConn) GetExtraData(key string) interface{} {
if data, ok := c.extraData[key]; ok {
return data
}
return nil
}