-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.go
74 lines (66 loc) · 1.71 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
package main
import (
"time"
)
type Message struct {
Data string `json:"data"`
RoomId string `json:"room_id"`
SenderId string `json:"sender_id"`
SentAt time.Time `json:"sent_at"`
JoiningChat bool `json:"joining_chat"`
LeavingChat bool `json:"leaving_chat"`
}
// hub maintains the set of active connections and broadcasts messages to the connections.
type hub struct {
// Registered connections.
rooms map[string]map[*Subscriber]bool
// Inbound messages from the connections.
broadcast chan Message
// Register requests from the connections.
register chan *Subscriber
// Unregister requests from connections.
unregister chan *Subscriber
}
var h = hub{
broadcast: make(chan Message),
register: make(chan *Subscriber),
unregister: make(chan *Subscriber),
rooms: make(map[string]map[*Subscriber]bool),
}
func (h *hub) run() {
for {
select {
case subscriber := <-h.register:
roomSubscribers := h.rooms[subscriber.roomId]
if roomSubscribers == nil {
roomSubscribers = make(map[*Subscriber]bool)
h.rooms[subscriber.roomId] = roomSubscribers
}
h.rooms[subscriber.roomId][subscriber] = true
case subscriber := <-h.unregister:
roomSubscribers := h.rooms[subscriber.roomId]
if roomSubscribers != nil {
if _, ok := roomSubscribers[subscriber]; ok {
delete(roomSubscribers, subscriber)
close(subscriber.send)
if len(roomSubscribers) == 0 {
delete(h.rooms, subscriber.roomId)
}
}
}
case m := <-h.broadcast:
subscribers := h.rooms[m.RoomId]
for c := range subscribers {
select {
case c.send <- m:
default:
close(c.send)
delete(subscribers, c)
if len(subscribers) == 0 {
delete(h.rooms, m.RoomId)
}
}
}
}
}
}