-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrooms.go
120 lines (104 loc) · 1.96 KB
/
rooms.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
package etp
import "sync"
const (
idsRoom = "__id"
)
type Rooms struct {
mu sync.RWMutex
rooms map[string]map[string]*Conn
}
func newRooms() *Rooms {
return &Rooms{
rooms: make(map[string]map[string]*Conn),
}
}
func (s *Rooms) Get(connId string) (*Conn, bool) {
s.mu.RLock()
var (
conn *Conn
ok bool
)
idRoom, roomExist := s.rooms[idsRoom]
if roomExist {
conn, ok = idRoom[connId]
}
s.mu.RUnlock()
return conn, ok
}
func (s *Rooms) Join(conn *Conn, rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
conns[conn.Id()] = conn
} else {
s.rooms[room] = map[string]*Conn{
conn.Id(): conn,
}
}
}
s.mu.Unlock()
}
func (s *Rooms) LeaveByConnId(id string, rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
delete(conns, id)
if len(conns) == 0 {
delete(s.rooms, room)
}
}
}
s.mu.Unlock()
}
func (s *Rooms) Len(room string) int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.rooms[room])
}
func (s *Rooms) Clear(rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
delete(s.rooms, room)
}
s.mu.Unlock()
}
func (s *Rooms) Rooms() []string {
s.mu.RLock()
result := make([]string, 0, len(s.rooms))
for room := range s.rooms {
if room != idsRoom {
result = append(result, room)
}
}
s.mu.RUnlock()
return result
}
func (s *Rooms) ToBroadcast(rooms ...string) []*Conn {
s.mu.RLock()
result := make([]*Conn, 0)
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
for _, conn := range conns {
result = append(result, conn)
}
}
}
s.mu.RUnlock()
return result
}
func (s *Rooms) AllConns() []*Conn {
return s.ToBroadcast(idsRoom)
}
func (s *Rooms) add(conn *Conn) {
s.Join(conn, idsRoom)
}
func (s *Rooms) remove(conn *Conn) {
s.mu.Lock()
defer s.mu.Unlock()
for room, conns := range s.rooms {
delete(conns, conn.Id())
if len(conns) == 0 {
delete(s.rooms, room)
}
}
}