-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheventRouter.go
68 lines (59 loc) · 1.19 KB
/
eventRouter.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
package main
import (
"log"
)
type mapEvent struct {
Action string
Data any
}
type mapEventRouter struct {
connect chan chan mapEvent
disconnect chan chan mapEvent
events chan mapEvent
}
var (
globalEventRouter = newMapEventRouter()
)
func newMapEventRouter() *mapEventRouter {
return &mapEventRouter{
connect: make(chan chan mapEvent, 16),
disconnect: make(chan chan mapEvent, 16),
events: make(chan mapEvent, 256),
}
}
func (router *mapEventRouter) Run(exitchan <-chan struct{}) {
clients := map[chan mapEvent]bool{}
for {
select {
case <-exitchan:
for c := range clients {
close(c)
}
return
case c := <-router.connect:
clients[c] = true
case c := <-router.disconnect:
delete(clients, c)
close(c)
case e := <-router.events:
for c := range clients {
select {
case c <- e:
default:
log.Printf("Event %v dropped!", e.Action)
}
}
}
}
}
func (router *mapEventRouter) Connect() chan mapEvent {
c := make(chan mapEvent, 256)
router.connect <- c
return c
}
func (router *mapEventRouter) Disconnect(c chan mapEvent) {
router.disconnect <- c
}
func (router *mapEventRouter) Broadcast(e mapEvent) {
router.events <- e
}