-
Notifications
You must be signed in to change notification settings - Fork 3
/
broadcast.go
97 lines (81 loc) · 1.54 KB
/
broadcast.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
87
88
89
90
91
92
93
94
95
96
97
package examples
import (
. "github.com/danalex97/Speer/interfaces"
"fmt"
)
type BroadcastExample struct {
Transport
id string
parent string
members []string
time func() int
}
func (s *BroadcastExample) New(util NodeUtil) Node {
return &BroadcastExample{
Transport: util.Transport(),
id: util.Id(),
parent: util.Join(),
members: []string{util.Id()},
time: util.Time(),
}
}
func (s *BroadcastExample) root() bool {
return s.parent == ""
}
type Join struct {
id string
}
type NewMember struct {
id string
}
type SomeBroadcast struct {
ts int
list []string
from string
}
func (s *BroadcastExample) broadcast(m interface{}) {
for _, member := range s.members {
s.ControlSend(member, m)
}
}
func (s *BroadcastExample) OnJoin() {
if !s.root() {
s.ControlSend(s.parent, Join{
id: s.id,
})
}
}
func (s *BroadcastExample) OnNotify() {
select {
case m, _ := <-s.ControlRecv():
switch msg := m.(type) {
case Join:
if !s.root() {
// subscribe in the list of nodes
s.ControlSend(s.parent, msg)
} else {
// if the root receives a new node, broadcast the message
s.members = append(s.members, msg.id)
s.broadcast(NewMember{
id: msg.id,
})
}
case NewMember:
if !s.root() {
if msg.id != s.id {
s.members = append(s.members, msg.id)
s.broadcast(SomeBroadcast{
ts: s.time(),
list: s.members,
from: s.id,
})
}
}
case SomeBroadcast:
fmt.Println(s.id, "recv:", msg)
}
default:
}
}
func (s *BroadcastExample) OnLeave() {
}