/
tcpSession.go
251 lines (211 loc) · 6.53 KB
/
tcpSession.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package tcpLib
import (
"github.com/seabyte7/goToolkit/logLib"
"github.com/seabyte7/goToolkit/netLib/netType"
"go.uber.org/zap"
"io"
"net"
"sync"
"time"
)
const (
MaxHeartBeatIntervalMs = 5 * 1000 // 60s
)
type TcpSession struct {
ID uint32
sendMsgChan chan *ClientServerMsg
ReceiveMsgChan chan *ClientServerMsg // Referenced external out message channel
disconnectChanRef chan *TcpSession // Referenced external disconnected channel
readWriteCloseChan chan struct{} // The internal read/write channel is closed
conn net.Conn
receiveDataBuf []byte // recv data buffer
receiveBytes uint64 // recv bytes
sendBytes uint64 // send bytes
lastActiveTimeMs int64 // last active time
exitChan chan struct{}
closeOnce sync.Once
waitGroup sync.WaitGroup
}
func newServerSession(conn net.Conn, receiveMsgChan chan *ClientServerMsg, disconnectChan chan *TcpSession) *TcpSession {
return &TcpSession{
ID: acquireID(),
sendMsgChan: make(chan *ClientServerMsg, 512),
ReceiveMsgChan: receiveMsgChan,
disconnectChanRef: disconnectChan,
readWriteCloseChan: make(chan struct{}, 2),
conn: conn,
receiveDataBuf: make([]byte, 0),
receiveBytes: 0,
sendBytes: 0,
lastActiveTimeMs: time.Now().UnixMilli(),
exitChan: make(chan struct{}, 1),
}
}
func newClientSession(conn net.Conn, disconnectChan chan *TcpSession) *TcpSession {
return &TcpSession{
ID: acquireID(),
sendMsgChan: make(chan *ClientServerMsg, 512),
ReceiveMsgChan: make(chan *ClientServerMsg, 512),
disconnectChanRef: disconnectChan,
readWriteCloseChan: make(chan struct{}, 2),
conn: conn,
receiveDataBuf: make([]byte, 0),
receiveBytes: 0,
sendBytes: 0,
lastActiveTimeMs: time.Now().UnixMilli(),
exitChan: make(chan struct{}, 1),
}
}
func (this *TcpSession) Start() {
logLib.Zap().Info("session start", zap.Uint32("sessionID", this.ID))
go this.monitorThread()
go this.receiveThread()
go this.sendThread()
}
func (this *TcpSession) Stop() {
this.closeOnce.Do(func() {
logLib.Zap().Info("session stop", zap.Uint32("sessionID", this.ID))
close(this.exitChan)
if this.conn != nil {
this.conn.Close()
this.conn = nil
}
})
this.waitGroup.Wait()
}
func (this *TcpSession) monitorThread() {
this.waitGroup.Add(1)
defer this.waitGroup.Done()
select {
case <-this.exitChan:
return
case <-this.readWriteCloseChan:
this.disconnectChanRef <- this
return
}
}
func (this *TcpSession) receiveThread() {
this.waitGroup.Add(1)
defer this.waitGroup.Done()
logLib.Zap().Info("session receive thread start", zap.Uint32("sessionID", this.ID))
defer func() {
logLib.Zap().Info("session receive thread stop", zap.Uint32("sessionID", this.ID))
this.readWriteCloseChan <- struct{}{}
}()
for {
select {
case <-this.exitChan:
break
default:
receiveBuf := make([]byte, 1024)
count, err := this.conn.Read(receiveBuf)
if err != nil {
if err == io.EOF {
logLib.Sugar().Infof("session:%d read eof, socket closed.", this.ID)
return
}
logLib.Sugar().Infof("session:%d read error:%v", this.ID, err)
return
}
if count == 0 {
// If the caller wanted a zero byte read, return immediately
// without trying (but after acquiring the readLock).
// Otherwise syscall.Read returns 0, nil which looks like
// io.EOF.
// TODO(bradfitz): make it wait for readability? (Issue 15735)
// src/internal/poll/fd_unix.go
logLib.Zap().Error("session:%d read 0 byte", zap.Uint32("sessionID", this.ID))
return
}
this.receiveDataBuf = append(this.receiveDataBuf, receiveBuf[:count]...)
this.receiveBytes += uint64(count)
this.lastActiveTimeMs = time.Now().UnixMilli()
msgList := this.parseMessage()
for _, msg := range msgList {
switch msg.Cmd {
case netType.CmdHeartbeat:
this.OnReceiveHeartBeat()
case netType.CmdMsg:
this.ReceiveMsgChan <- NewClientServerMsg(this, msg)
default:
logLib.Zap().Error("session receive unknown cmd:%d", zap.Uint32("session", this.ID), zap.Uint8("cmd", msg.Cmd))
}
}
}
}
logLib.Zap().Info("session receive thread exit", zap.Uint32("sessionID", this.ID))
}
// parse message packet
func (this *TcpSession) parseMessage() []*netType.NetMsg {
msgList := make([]*netType.NetMsg, 0, 4)
maxTryCount := 4
for i := 0; i < maxTryCount; i++ {
if len(this.receiveDataBuf) == 0 {
break
}
msgLen := netType.BytesToUint32(this.receiveDataBuf[:netType.MsgLengthLen])
bufLen := len(this.receiveDataBuf)
if msgLen < uint32(bufLen) {
return msgList
}
cmd := netType.BytesToUint8(this.receiveDataBuf[netType.MsgLengthLen : netType.MsgLengthLen+netType.MsgCmdLen])
msg := netType.NewNetMsg(cmd, this.receiveDataBuf[netType.MsgHeaderLen:msgLen])
msgList = append(msgList, msg)
this.receiveDataBuf = this.receiveDataBuf[msgLen:]
}
return msgList
}
func (this *TcpSession) sendThread() {
this.waitGroup.Add(1)
defer this.waitGroup.Done()
logLib.Zap().Info("session send thread start", zap.Uint32("sessionID", this.ID))
defer func() {
logLib.Zap().Info("session send thread stop", zap.Uint32("sessionID", this.ID))
this.readWriteCloseChan <- struct{}{}
}()
for {
willExit := false
select {
case <-this.exitChan:
willExit = true
break
case msg := <-this.sendMsgChan:
count, err := this.conn.Write(msg.ToBytes())
if err != nil {
logLib.Sugar().Errorf("session:%d write error:%v", this.ID, err)
break
}
logLib.Sugar().Debugf("session:%d write msg:%v, length:%d", this.ID, msg, count)
this.sendBytes += uint64(count)
this.lastActiveTimeMs = time.Now().UnixMilli()
}
if willExit {
break
}
}
logLib.Zap().Info("session send thread exit", zap.Uint32("sessionID", this.ID))
}
func (this *TcpSession) SendHeartBeatMsg() {
this.sendMsgByCmd(netType.CmdHeartbeat, []byte{})
}
func (this *TcpSession) SendMsg(data []byte) {
this.sendMsgByCmd(netType.CmdMsg, data)
}
func (this *TcpSession) sendMsgByCmd(cmd uint8, data []byte) {
clientServerMsg := NewClientServerMsg(this, netType.NewNetMsg(cmd, data))
this.sendMsgChan <- clientServerMsg
}
func (this *TcpSession) HeartBeat() {
this.SendHeartBeatMsg()
}
func (this *TcpSession) OnReceiveHeartBeat() {
this.lastActiveTimeMs = time.Now().UnixMilli()
logLib.Sugar().Debugf("session:%d recv heartbeat", this.ID)
}
func (this *TcpSession) IsActive() bool {
nowTime := time.Now()
if nowTime.UnixMilli()-this.lastActiveTimeMs > MaxHeartBeatIntervalMs {
return false
}
return true
}