forked from nknorg/nnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (72 loc) · 1.63 KB
/
main.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
// This example shows how to create and join a nnet with multiple nodes.
// Run with default options: go run main.go
// Show usage: go run main.go -h
package main
import (
"flag"
"os"
"os/signal"
"sync"
"time"
"github.com/nknorg/nnet"
"github.com/nknorg/nnet/log"
)
func create(transport string, port uint16) (*nnet.NNet, error) {
conf := &nnet.Config{
Port: port,
Transport: transport,
BaseStabilizeInterval: 233 * time.Millisecond,
}
nn, err := nnet.NewNNet(nil, conf)
if err != nil {
return nil, err
}
return nn, nil
}
func main() {
transportPtr := flag.String("t", "tcp", "transport type, tcp or kcp")
numNodesPtr := flag.Int("n", 10, "number of nodes")
flag.Parse()
if *numNodesPtr < 1 {
log.Error("Number of nodes must be greater than 0")
return
}
const createPort uint16 = 23333
nnets := make([]*nnet.NNet, 0)
for i := 0; i < *numNodesPtr; i++ {
nn, err := create(*transportPtr, createPort+uint16(i))
if err != nil {
log.Error(err)
return
}
nnets = append(nnets, nn)
}
for i := 0; i < len(nnets); i++ {
time.Sleep(112358 * time.Microsecond)
err := nnets[i].Start(i == 0)
if err != nil {
log.Error(err)
return
}
if i > 0 {
err = nnets[i].Join(nnets[0].GetLocalNode().Addr)
if err != nil {
log.Error(err)
return
}
}
}
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
<-signalChan
log.Info("\nReceived an interrupt, stopping...\n")
var wg sync.WaitGroup
for i := 0; i < len(nnets); i++ {
wg.Add(1)
go func(nn *nnet.NNet) {
nn.Stop(nil)
wg.Done()
}(nnets[len(nnets)-1-i])
}
wg.Wait()
}