-
Notifications
You must be signed in to change notification settings - Fork 2
/
hub.go
48 lines (43 loc) · 1016 Bytes
/
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
package pusher
import "github.com/FlowerWrong/pusher/log"
// Hub maintains the set of active sessions and broadcasts messages to the sessions.
type Hub struct {
sessions map[*Session]bool
broadcast chan []byte
register chan *Session
unregister chan *Session
}
// NewHub builds new hub instance
func NewHub() *Hub {
return &Hub{
broadcast: make(chan []byte),
register: make(chan *Session),
unregister: make(chan *Session),
sessions: make(map[*Session]bool),
}
}
// Run hub
func (h *Hub) Run() {
for {
select {
case session := <-h.register:
h.sessions[session] = true
err := AddUser(session.socketID)
if err != nil {
log.Error(err)
}
log.Infoln(session.socketID, "joined")
case session := <-h.unregister:
h.cleanSession(session)
case message := <-h.broadcast:
for session := range h.sessions {
session.Send(message)
}
}
}
}
func (h *Hub) cleanSession(session *Session) {
if _, ok := h.sessions[session]; ok {
delete(h.sessions, session)
}
}