-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchannel.go
171 lines (156 loc) · 4.15 KB
/
channel.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
package cim
import (
"cirno-im/constants"
"cirno-im/logger"
"errors"
"fmt"
"github.com/panjf2000/ants/v2"
"sync/atomic"
"time"
)
type ChannelImpl struct {
id string
Conn
meta Meta
writeChan chan []byte
writeWait time.Duration
readWait time.Duration
gPool *ants.Pool
state int32 // 0 init 1 start 2 closed
}
func NewChannel(id string, meta Meta, conn Conn, gpool *ants.Pool) Channel {
ch := &ChannelImpl{
id: id,
Conn: conn,
meta: meta,
writeChan: make(chan []byte, 5),
writeWait: constants.DefaultWriteWait, //default value
readWait: constants.DefaultReadWait,
gPool: gpool,
state: 0,
}
go func() {
err := ch.writeLoop()
if err != nil {
logger.WithFields(logger.Fields{
"module": "ChannelImpl",
"id": id,
}).Info(err)
}
}()
return ch
}
func (ch *ChannelImpl) writeLoop() error {
log := logger.WithFields(logger.Fields{
"module": "ChannelImpl",
"func": "writeloop",
"id": ch.id,
})
defer func() {
log.Debugf("channel %s writeloop exited", ch.id)
}()
for payload := range ch.writeChan {
err := ch.WriteFrame(OpBinary, payload)
if err != nil {
return err
}
chanlen := len(ch.writeChan)
for i := 0; i < chanlen; i++ {
payload = <-ch.writeChan
err := ch.WriteFrame(OpBinary, payload)
if err != nil {
return err
}
}
err = ch.Flush()
if err != nil {
return err
}
}
return nil
}
// ID id simpling server
func (ch *ChannelImpl) ID() string { return ch.id }
// Push 异步写数据
func (ch *ChannelImpl) Push(payload []byte) error {
if atomic.LoadInt32(&ch.state) != 1 {
return fmt.Errorf("channel %s has closed", ch.id)
}
// 异步写
ch.writeChan <- payload
return nil
}
// Close 关闭连接
func (ch *ChannelImpl) Close() error {
if !atomic.CompareAndSwapInt32(&ch.state, 1, 2) {
return fmt.Errorf("channel has started")
}
close(ch.writeChan)
return nil
}
// SetWriteWait 设置写超时
func (ch *ChannelImpl) SetWriteWait(writeWait time.Duration) {
if writeWait == 0 {
return
}
ch.writeWait = writeWait
}
func (ch *ChannelImpl) SetReadWait(readwait time.Duration) {
if readwait == 0 {
return
}
ch.readWait = readwait
}
// Declare a function called Readloop that belongs to the ChannelImpl struct.
// This function takes in a MessageListener as a parameter and returns an error (if there is one).
func (ch *ChannelImpl) ReadLoop(lst MessageListener) error {
// Perform an atomic compare-and-swap operation on ch.state. If the current value is 0, set it to 1.
// If it's already 1, return an error indicating that the channel has already started.
if !atomic.CompareAndSwapInt32(&ch.state, 0, 1) {
return fmt.Errorf("channel has started")
}
// Create a new logger object with some fields filled out.
log := logger.WithFields(logger.Fields{
"struct": "ChannelImpl",
"func": "Readloop",
"id": ch.id,
})
// Start an infinite loop.
for {
// Set a read deadline for the channel.
_ = ch.SetReadDeadline(time.Now().Add(ch.readWait))
// Attempt to read a frame from the channel.
frame, err := ch.ReadFrame()
if err != nil {
// If reading the frame failed, log the error and return it.
log.Info(err)
return err
}
if frame.GetOpCode() == OpClose {
// If the received frame has an OpCode of OpClose, return an error indicating that the remote side closed the channel.
return errors.New("remote side closed the channel")
}
if frame.GetOpCode() == OpPing {
// If the received frame has an OpCode of OpPing, log that we received a ping and respond with a pong.
log.Trace("recv a ping; resp with a pong")
_ = ch.WriteFrame(OpPong, nil)
_ = ch.Flush()
continue
}
payload := frame.GetPayload()
if len(payload) == 0 {
// If the payload is empty, skip to the next iteration of the loop.
continue
}
err = ch.gPool.Submit(func() {
// Submit a new task to the gpool (which is an instance of a goroutine pool).
// This task calls lst.Receive with the channel and payload as parameters.
lst.Receive(ch, payload)
})
if err != nil {
// If submitting the task to the gpool failed, return an error.
return err
}
}
}
func (ch *ChannelImpl) GetMetadata() Meta { return ch.meta }