-
Notifications
You must be signed in to change notification settings - Fork 5
/
channel.go
95 lines (78 loc) · 1.54 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
package websocket
import (
"sync"
)
// Channel represent group of connections (similar to group in socket.io).
type Channel struct {
id string
connections map[*Conn]bool
delConn chan *Conn
mu sync.Mutex
}
func newChannel(id string) *Channel {
c := Channel{
id: id,
connections: make(map[*Conn]bool),
delConn: make(chan *Conn),
}
go func() {
for {
select {
case conn := <-c.delConn:
c.mu.Lock()
_ = conn.Close()
delete(c.connections, conn)
c.mu.Unlock()
}
}
}()
return &c
}
// Count return number of live connections in channel.
func (c *Channel) Count() int {
c.mu.Lock()
defer c.mu.Unlock()
count := 0
for con := range c.connections {
if con.conn != nil {
count++
}
}
return count
}
// ID return channel id.
func (c *Channel) ID() string {
return c.id
}
// Add connection to channel.
func (c *Channel) Add(conn *Conn) {
c.mu.Lock()
c.connections[conn] = true
c.mu.Unlock()
}
// Remove connection from channel.
func (c *Channel) Remove(conn *Conn) {
c.mu.Lock()
delete(c.connections, conn)
c.mu.Unlock()
}
// Emit message to all connections in channel.
func (c *Channel) Emit(name string, data interface{}) {
c.mu.Lock()
for con := range c.connections {
if err := con.Emit(name, data); err != nil {
_ = con.Close()
c.mu.Unlock()
c.Remove(con)
c.mu.Lock()
}
}
c.mu.Unlock()
}
// Purge remove all connections from channel.
func (c *Channel) Purge() {
c.mu.Lock()
c.connections = make(map[*Conn]bool)
c.delConn = make(chan *Conn)
c.mu.Unlock()
}