/
channel.go
87 lines (75 loc) · 1.61 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
package comet
import (
"sync"
"github.com/youminxue/euler/api/comet/grpc"
"github.com/youminxue/euler/pkg/bufio"
)
// Channel used by message pusher send msg to write goroutine.
type Channel struct {
Room *Room
CliProto Ring
signal chan *grpc.Proto
Writer bufio.Writer
Reader bufio.Reader
Next *Channel
Prev *Channel
Mid int64
Key string
IP string
watchOps map[int32]struct{}
mutex sync.RWMutex
}
// NewChannel new a channel.
func NewChannel(cli, svr int) *Channel {
c := new(Channel)
c.CliProto.Init(cli)
c.signal = make(chan *grpc.Proto, svr)
c.watchOps = make(map[int32]struct{})
return c
}
// Watch watch a operation.
func (c *Channel) Watch(accepts ...int32) {
c.mutex.Lock()
for _, op := range accepts {
c.watchOps[op] = struct{}{}
}
c.mutex.Unlock()
}
// UnWatch unwatch an operation
func (c *Channel) UnWatch(accepts ...int32) {
c.mutex.Lock()
for _, op := range accepts {
delete(c.watchOps, op)
}
c.mutex.Unlock()
}
// NeedPush verify if in watch.
func (c *Channel) NeedPush(op int32) bool {
c.mutex.RLock()
if _, ok := c.watchOps[op]; ok {
c.mutex.RUnlock()
return true
}
c.mutex.RUnlock()
return false
}
// Push server push message.
func (c *Channel) Push(p *grpc.Proto) (err error) {
select {
case c.signal <- p:
default:
}
return
}
// Ready check the channel ready or close?
func (c *Channel) Ready() *grpc.Proto {
return <-c.signal
}
// Signal send signal to the channel, protocol ready.
func (c *Channel) Signal() {
c.signal <- grpc.ProtoReady
}
// Close close the channel.
func (c *Channel) Close() {
c.signal <- grpc.ProtoFinish
}