-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (69 loc) · 1.84 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
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/libp2p/go-libp2p"
peerstore "github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p/p2p/protocol/ping"
multiaddr "github.com/multiformats/go-multiaddr"
)
func main() {
// create a background context (i.e. one that never cancels)
ctx := context.Background()
// start a libp2p node that listens on a random local TCP port,
// but without running the built-in ping protocol
node, err := libp2p.New(ctx,
libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"),
libp2p.Ping(false),
)
if err != nil {
panic(err)
}
// configure our own ping protocol
pingService := &ping.PingService{Host: node}
node.SetStreamHandler(ping.ID, pingService.PingHandler)
// print the node's PeerInfo in multiaddr format
peerInfo := peerstore.AddrInfo{
ID: node.ID(),
Addrs: node.Addrs(),
}
addrs, err := peerstore.AddrInfoToP2pAddrs(&peerInfo)
if err != nil {
panic(err)
}
fmt.Println("libp2p node address:", addrs[0])
// if a remote peer has been passed on the command line, connect to it
// and send it 5 ping messages, otherwise wait for a signal to stop
if len(os.Args) > 1 {
addr, err := multiaddr.NewMultiaddr(os.Args[1])
if err != nil {
panic(err)
}
peer, err := peerstore.AddrInfoFromP2pAddr(addr)
if err != nil {
panic(err)
}
if err := node.Connect(ctx, *peer); err != nil {
panic(err)
}
fmt.Println("sending 5 ping messages to", addr)
ch := pingService.Ping(ctx, peer.ID)
for i := 0; i < 5; i++ {
res := <-ch
fmt.Println("pinged", addr, "in", res.RTT)
}
} else {
// wait for a SIGINT or SIGTERM signal
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
fmt.Println("Received signal, shutting down...")
}
// shut the node down
if err := node.Close(); err != nil {
panic(err)
}
}