-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
84 lines (74 loc) · 2.14 KB
/
app.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
package main
import (
"bufio"
"context"
"crypto/rand"
"flag"
"fmt"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/peerstore"
"github.com/multiformats/go-multiaddr"
"log"
"os"
)
func makeHost(port int) (host.Host, error) {
privateKey, _, _ := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, rand.Reader)
hostMultiAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", port))
return libp2p.New(
libp2p.ListenAddrs(hostMultiAddr),
libp2p.Identity(privateKey),
)
}
func startPeer(host host.Host, streamHandler network.StreamHandler) {
host.SetStreamHandler("/chat/0.0.1", streamHandler)
}
func startPeerAndConnect(host host.Host, targetAddr multiaddr.Multiaddr) (network.Stream, error) {
targetAddrInfo, _ := peer.AddrInfoFromP2pAddr(targetAddr)
host.Peerstore().AddAddrs(targetAddrInfo.ID, targetAddrInfo.Addrs, peerstore.PermanentAddrTTL)
stream, _ := host.NewStream(context.Background(), targetAddrInfo.ID, "/chat/0.0.1")
return stream, nil
}
func main() {
sourcePort := flag.Int("port", 0, "Source port number")
dest := flag.String("dest", "", "Destination multiaddr string")
flag.Parse()
host, _ := makeHost(*sourcePort)
if *dest == "" {
startPeer(host, handleStream)
log.Printf("HEY I AM /ip4/0.0.0.0/tcp/%v/p2p/%s JOIN ME !!!\n", *sourcePort, host.ID().String())
} else {
multiAddr, _ := multiaddr.NewMultiaddr(*dest)
stream, _ := startPeerAndConnect(host, multiAddr)
handleStream(stream)
}
select {}
}
func handleStream(s network.Stream) {
rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s))
go readData(rw)
go writeData(rw)
}
func writeData(rw *bufio.ReadWriter) {
stdReader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
sendData, _ := stdReader.ReadString('\n')
rw.WriteString(fmt.Sprintf("%s\n", sendData))
rw.Flush()
}
}
func readData(rw *bufio.ReadWriter) {
for {
str, _ := rw.ReadString('\n')
if str == "" {
return
}
if str != "\n" {
fmt.Printf("(INCOMING) %s> ", str)
}
}
}