-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distributor.go
75 lines (57 loc) · 991 Bytes
/
distributor.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
package main
import (
"github.com/chabad360/go-osc/osc"
"sync"
)
type Distributor struct {
l map[string]chan []byte
m sync.RWMutex
b *osc.Bundle
bM sync.Mutex
}
func (d *Distributor) Listen(key string) <-chan []byte {
ch := make(chan []byte)
d.m.Lock()
if och, ok := d.l[key]; ok {
close(och)
}
d.l[key] = ch
d.m.Unlock()
return ch
}
func (d *Distributor) Close(key string) {
d.m.Lock()
if och, ok := d.l[key]; ok {
close(och)
}
delete(d.l, key)
d.m.Unlock()
}
func (d *Distributor) Publish(m *osc.Message) {
d.bM.Lock()
if d.b == nil {
d.b = &osc.Bundle{Timetag: osc.NewImmediateTimetag()}
}
d.b.Elements = append(d.b.Elements, m)
d.bM.Unlock()
}
func (d *Distributor) Send() {
d.bM.Lock()
b, err := d.b.MarshalBinary()
if err != nil {
panic(err)
}
d.b = nil
d.publish(b)
d.bM.Unlock()
}
func (d *Distributor) publish(v []byte) {
d.m.RLock()
for _, ch := range d.l {
select {
case ch <- v:
default:
}
}
d.m.RUnlock()
}