-
Notifications
You must be signed in to change notification settings - Fork 1
/
room.go
82 lines (67 loc) · 1.22 KB
/
room.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
package main
import (
"sync"
)
type Room struct {
conns map[string]*Conn
mutex *sync.RWMutex
}
func NewRoom() *Room {
return &Room{conns: make(map[string]*Conn), mutex: &sync.RWMutex{}}
}
func (r *Room) Add(conn *Conn) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.conns[conn.id] = conn
}
func (r *Room) Rm(conn *Conn) {
r.mutex.Lock()
defer r.mutex.Unlock()
delete(r.conns, conn.id)
conn.Close()
}
func (r *Room) Get(id string) (*Conn, bool) {
r.mutex.RLock()
defer r.mutex.RUnlock()
if conn, ok := r.conns[id]; ok {
return conn, true
}
return nil, false
}
func (r *Room) Len() int {
r.mutex.RLock()
defer r.mutex.RUnlock()
return len(r.conns)
}
func (r *Room) IsEmpty() bool {
return r.Len() == 0
}
func (r *Room) Close() {
r.mutex.Lock()
defer r.mutex.Unlock()
for _, conn := range r.conns {
delete(r.conns, conn.id)
conn.Close()
}
}
func (r *Room) Send(msg *Message) {
if len(msg.To) == 0 {
r.broadcast(msg)
} else {
r.send(msg)
}
}
func (r *Room) broadcast(msg *Message) {
r.mutex.RLock()
defer r.mutex.RUnlock()
for _, conn := range r.conns {
if conn.id != msg.From {
conn.Send(msg)
}
}
}
func (r *Room) send(msg *Message) {
if conn, ok := r.Get(msg.To); ok {
conn.Send(msg)
}
}