-
Notifications
You must be signed in to change notification settings - Fork 30
/
main.go
81 lines (72 loc) · 2.18 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
package main
import (
"Network-go/network/bcast"
"Network-go/network/localip"
"Network-go/network/peers"
"flag"
"fmt"
"os"
"time"
)
// We define some custom struct to send over the network.
// Note that all members we want to transmit must be public. Any private members
// will be received as zero-values.
type HelloMsg struct {
Message string
Iter int
}
func main() {
// Our id can be anything. Here we pass it on the command line, using
// `go run main.go -id=our_id`
var id string
flag.StringVar(&id, "id", "", "id of this peer")
flag.Parse()
// ... or alternatively, we can use the local IP address.
// (But since we can run multiple programs on the same PC, we also append the
// process ID)
if id == "" {
localIP, err := localip.LocalIP()
if err != nil {
fmt.Println(err)
localIP = "DISCONNECTED"
}
id = fmt.Sprintf("peer-%s-%d", localIP, os.Getpid())
}
// We make a channel for receiving updates on the id's of the peers that are
// alive on the network
peerUpdateCh := make(chan peers.PeerUpdate)
// We can disable/enable the transmitter after it has been started.
// This could be used to signal that we are somehow "unavailable".
peerTxEnable := make(chan bool)
go peers.Transmitter(15647, id, peerTxEnable)
go peers.Receiver(15647, peerUpdateCh)
// We make channels for sending and receiving our custom data types
helloTx := make(chan HelloMsg)
helloRx := make(chan HelloMsg)
// ... and start the transmitter/receiver pair on some port
// These functions can take any number of channels! It is also possible to
// start multiple transmitters/receivers on the same port.
go bcast.Transmitter(16569, helloTx)
go bcast.Receiver(16569, helloRx)
// The example message. We just send one of these every second.
go func() {
helloMsg := HelloMsg{"Hello from " + id, 0}
for {
helloMsg.Iter++
helloTx <- helloMsg
time.Sleep(1 * time.Second)
}
}()
fmt.Println("Started")
for {
select {
case p := <-peerUpdateCh:
fmt.Printf("Peer update:\n")
fmt.Printf(" Peers: %q\n", p.Peers)
fmt.Printf(" New: %q\n", p.New)
fmt.Printf(" Lost: %q\n", p.Lost)
case a := <-helloRx:
fmt.Printf("Received: %#v\n", a)
}
}
}