1.官网https://libp2p.io/
2.GitHub上源码:
https://github.com/libp2p/go-libp2p
https://github.com/libp2p/zeroconf
3.go-libp2p/examples/chat-with-mdns/
用于同一网段IP间通信,跨网段需要改源码
./chat-with-mdns -port 6666
./chat-with-mdns -port 6668
- zeroconf/examples/resolv/
用于搜索启动mdns服务的设备,支持跨网段
./resolv
5.改动:将zeroconfig改为通过启动mdns服务方式,搜索附近设备,支持同网段间通信
1.创建密钥
prvKey, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r)
2.创建libp2p主机
// 0.0.0.0 will listen on any interface device.
host, err := libp2p.New(
libp2p.ListenAddrs(sourceMultiAddr),
libp2p.Identity(prvKey),
)
3.创建流句柄
// Set a function as stream handler.
// This function is called when a peer initiates a connection and starts a
stream with this peer.
host.SetStreamHandler(protocol.ID(cfg.ProtocolID), handleStream)
4.初始化mdns服务
peerChan := initMDNS(host, cfg.RendezvousString)
5.连接
for peer := range peerChan{
fmt.Println("Found peer:", peer, ", connecting")
PeerSlice = append(PeerSlice, peer)
//PeerSlice := make([]peer.AddrInfo, 10)
go func() {
for i, v := range PeerSlice {
fmt.Printf("i=%v, peerslice = %v\n",i, v)
str1 := v.String()
//fmt.Printf("str1 = %v\n",str1)
str2 := strings.Split(str1, "/")
//fmt.Printf("str2[0]=%s\n", str2[0])
//fmt.Printf("str2[1]=%s\n", str2[1])
//fmt.Printf("str2[2]=%s\n", str2[2])
//fmt.Printf("str2[3]=%s\n", str2[3])
//fmt.Printf("str2[4]=%s\n", str2[4])
//str3 := "192.168.9.100"
//if "192.168.1.100" == str2[2]
if cfg.FindIp == str2[2]{
//fmt.Println("get it \n\n\n")
fmt.Println("Found peer:", v, ", connecting")
if err := host.Connect(ctx, v); err != nil {
fmt.Println("Connection failed:", err)
}
// open a stream, this stream will be handled by handleStream other end
stream, err := host.NewStream(ctx, v.ID,
protocol.ID(cfg.ProtocolID))
if err != nil {
fmt.Println("Stream open failed", err)
} else {
rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))
go writeData(rw)
go readData(rw)
fmt.Println("Connected to:", v)
}
}
}
}()
}