/
main.go
101 lines (81 loc) · 1.98 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
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"fmt"
"io/ioutil"
"os"
"time"
"golang.org/x/net/context"
"github.com/ipfs/go-libp2p-peer"
"github.com/ipfs/go-libp2p-peerstore"
"github.com/ipfs/go-libp2p/p2p/metrics"
"github.com/ipfs/go-libp2p/p2p/net"
"github.com/ipfs/go-libp2p/p2p/net/swarm"
ma "github.com/jbenet/go-multiaddr"
)
func Fatal(i interface{}) {
fmt.Println(i)
os.Exit(1)
}
func dialAndSend(s *swarm.Swarm, target peer.ID) {
str, err := s.NewStreamWithPeer(context.Background(), target)
if err != nil {
Fatal(err)
}
fmt.Fprintln(str, "Hello World!")
str.Close()
}
func main() {
if len(os.Args) < 3 {
fmt.Println("to run a listener, specify peer id and listen port")
fmt.Println("to run a dialer, specify our id and port, and the target id and port")
Fatal("must specify at least three args")
}
// any valid multihash works if we have the secio disabled
id, err := peer.IDB58Decode(os.Args[1])
if err != nil {
Fatal(err)
}
addr, err := ma.NewMultiaddr("/ip4/0.0.0.0/tcp/" + os.Args[2])
if err != nil {
Fatal(err)
}
var dialPeer peer.ID
var dialAddr ma.Multiaddr
if len(os.Args) >= 5 {
p, err := peer.IDB58Decode(os.Args[3])
if err != nil {
Fatal(err)
}
a, err := ma.NewMultiaddr("/ip4/127.0.0.1/tcp/" + os.Args[4])
if err != nil {
Fatal(err)
}
dialPeer = p
dialAddr = a
}
// new empty peerstore
pstore := peerstore.NewPeerstore()
ctx := context.Background()
// construct ourselves a swarmy thingy
s, err := swarm.NewSwarm(ctx, []ma.Multiaddr{addr}, id, pstore, metrics.NewBandwidthCounter())
if err != nil {
Fatal(err)
}
// if we are the dialer, do a dial!
if dialAddr != nil {
// add the targets address to the peerstore
pstore.AddAddr(dialPeer, dialAddr, peer.PermanentAddrTTL)
dialAndSend(s, dialPeer)
return
}
// set a function to handle streams
s.SetStreamHandler(func(st net.Stream) {
out, err := ioutil.ReadAll(st)
if err != nil {
Fatal(err)
}
fmt.Println(string(out))
})
// just wait around
time.Sleep(time.Hour)
}