-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
86 lines (72 loc) · 1.77 KB
/
hub.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
package socketconsumer
import (
"github.com/gorilla/websocket"
)
type Hub struct {
// Registered consumers
consumers map[string]*ConsumerController
// Registered groups
groups map[string]*group
// upgrader
upgrader websocket.Upgrader
}
// newHub creates a new hub
func NewHub(upgrader websocket.Upgrader) *Hub {
return &Hub{
consumers: make(map[string]*ConsumerController),
groups: make(map[string]*group),
upgrader: upgrader,
}
}
// Register consumer
func (hub *Hub) RegisterConsumer(c *ConsumerController) {
hub.consumers[c.getId()] = c
}
// Unregister consumer
func (hub *Hub) UnregisterConsumer(c *ConsumerController) {
delete(hub.consumers, c.getId())
}
// Get consumer by id
func (hub *Hub) GetConsumer(id string) *ConsumerController {
if c, ok := hub.consumers[id]; ok {
return c
}
return nil
}
// Has consumer
func (hub *Hub) HasConsumer(id string) bool {
_, ok := hub.consumers[id]
return ok
}
// Send to consumer
func (hub *Hub) Send(id string, message *Message) {
if c, ok := hub.consumers[id]; ok {
c.send(message)
}
}
// Add consumer to group
func (hub *Hub) GroupAdd(id string, c *Consumer) {
if _, ok := hub.groups[id]; !ok {
hub.groups[id] = newGroup(id)
}
hub.groups[id].addConsumer(c)
}
// Discard consumer from group and delete empty group
func (hub *Hub) GroupDiscard(id string, c *Consumer) {
hub.groups[id].removeConsumer(c)
if hub.groups[id].isEmpty() {
delete(hub.groups, id)
}
}
// Send to group
func (hub *Hub) GroupSend(id string, message *Message) {
if _, ok := hub.groups[id]; ok {
hub.groups[id].broadcast(message)
}
}
// Send to group except consumer
func (hub *Hub) GroupSendExcept(id string, message *Message, except *Consumer) {
if _, ok := hub.groups[id]; ok {
hub.groups[id].broadcastExcept(message, except)
}
}