使用AsyncRust构建简单的P2P节点P2P简介P2P:peer-to-peerP2P是一种网络技术,可以在不同的计算机之间共享各种计算资源,如CPU、网络带宽和存储。P2P是当今用户在线共享文件(如音乐、图像和其他数字媒体)的一种非常常用的方法。Bittorre
注意:多路复用在后端服务开发中很常见,其中客户端可以与服务器建立底层网络连接,然后通过底层网络连接多路复用不同的流(每个流具有唯一的端口号)。
P2P Node
PeerId: 12d3k.....
~/rust via 🅒 base
➜ cargo new p2p
Created binary (application) `p2p` package
~/rust via 🅒 base
➜ cd p2p
p2p on master [?] via 🦀 1.67.1 via 🅒 base
➜ c # code .
p2p on master [?] via 🦀 1.67.1 via 🅒 base
➜
Cmake
把 cmake 的路径添加到 PATH
~ via 🅒 base
➜ cmake
Usage
cmake [options] <path-to-source>
cmake [options] <path-to-existing-build>
cmake [options] -S <path-to-source> -B <path-to-build>
Specify a source directory to (re-)generate a build system for it in the
current working directory. Specify an existing build directory to
re-generate its build system.
Run 'cmake --help' for more information.
~ via 🅒 base
➜
use libp2p::{identity, PeerId};
#[tokio::main]
async fn main() {
let new_key = identity::Keypair::generate_ed25519();
let new_peer_id = PeerId::from(new_key.public());
println!("New Peer ID is: {:?}", new_peer_id);
// New Peer ID is: PeerId("12D3KooWF9nTF7cBU63Ac6ZEnvgzisRqjLwkc8BdM56Axxxxxxxx")
}
问题解决:
代码
use libp2p::futures::StreamExt; // 异步流有关
use libp2p::swarm::{DummyBehaviour, Swarm, SwarmEvent};
use libp2p::{identity, PeerId};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let new_key = identity::Keypair::generate_ed25519();
let new_peer_id = PeerId::from(new_key.public());
println!("New Peer ID is: {:?}", new_peer_id);
let behaviour = DummyBehaviour::default(); // 创建 网络行为
let transport = libp2p::development_transport(new_key).await?; // 使用密钥对创建传输
let mut swarm = Swarm::new(transport, behaviour, new_peer_id); // 创建Swarm
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
loop {
match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on local Address {:?}", address)
}
_ => {}
}
}
}
Cargo.toml
[package]
name = "p2p"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
libp2p = "0.46.1"
tokio ={ version = "1.19.2", features = ["full"]}
运行
p2p on master [?] is 📦 0.1.0 via 🦀 1.67.1 via 🅒 base
➜ cargo run
Compiling p2p v0.1.0 (/Users/qiaopengjun/rust/p2p)
Finished dev [unoptimized + debuginfo] target(s) in 3.17s
Running `target/debug/p2p`
New Peer ID is: PeerId("12D3KooWEzm5roUNjRgY2NfvFQBRhfYjRLsBQaDnDHdTBArhG3Qz")
Listening on local Address "/ip4/127.0.0.1/tcp/51422"
Listening on local Address "/ip4/192.168.0.100/tcp/51422"
p2p on master [?] is 📦 0.1.0 via 🦀 1.67.1 via 🅒 base
➜ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.15s
Running `target/debug/p2p`
New Peer ID is: PeerId("12D3KooWEqEEHHZYTv3QeEMjGdyy5HrW2u43oPGDyfj118QRGDcA")
Listening on local Address "/ip4/127.0.0.1/tcp/51426"
Listening on local Address "/ip4/192.168.0.100/tcp/51426"
use libp2p::futures::StreamExt; // 异步流有关
use libp2p::ping::{Ping, PingConfig};
use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::{identity, Multiaddr, PeerId};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let new_key = identity::Keypair::generate_ed25519();
let new_peer_id = PeerId::from(new_key.public());
println!("New Peer ID is: {:?}", new_peer_id);
let transport = libp2p::development_transport(new_key).await?; // 使用密钥对创建传输
let behaviour = Ping::new(PingConfig::new().with_keep_alive(true)); // 创建 网络行为
let mut swarm = Swarm::new(transport, behaviour, new_peer_id); // 创建Swarm
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
// 本地节点向远程节点发出连接 从命令行输入的参数取出
if let Some(remote_peer) = std::env::args().nth(1) {
let remote_peer_multiaddr: Multiaddr = remote_peer.parse()?;
swarm.dial(remote_peer_multiaddr)?;
println!("Dialed remote peer: {:?}", remote_peer); // 打印远程地址
}
loop {
match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on local Address {:?}", address)
}
SwarmEvent::Behaviour(event) => println!("Event received from peer is {:?}", event),
_ => {}
}
}
}
运行
p2p on master [?] is 📦 0.1.0 via 🦀 1.67.1 via 🅒 base took 17m 31.5s
➜ cargo run
Compiling p2p v0.1.0 (/Users/qiaopengjun/rust/p2p)
Finished dev [unoptimized + debuginfo] target(s) in 2.35s
Running `target/debug/p2p`
New Peer ID is: PeerId("12D3KooWEnxeFEWM3fvcNw8HV1tWojkmTaNVhrQfhPgL2REnngBS")
Listening on local Address "/ip4/127.0.0.1/tcp/51574"
Listening on local Address "/ip4/192.168.0.100/tcp/51574"
Event received from peer is Event { peer: PeerId("12D3KooWCEnQmgt6o5q9no2EfbpCU1xtyRFgRHjWJTiFdC3PTjB8"), result: Ok(Pong) }
Event received from peer is Event { peer: PeerId("12D3KooWCEnQmgt6o5q9no2EfbpCU1xtyRFgRHjWJTiFdC3PTjB8"), result: Ok(Ping { rtt: 193.542µs }) }
p2p on master [?] is 📦 0.1.0 via 🦀 1.67.1 via 🅒 base took 17m 3.0s
➜ cargo run /ip4/127.0.0.1/tcp/51574
Finished dev [unoptimized + debuginfo] target(s) in 0.15s
Running `target/debug/p2p /ip4/127.0.0.1/tcp/51574`
New Peer ID is: PeerId("12D3KooWCEnQmgt6o5q9no2EfbpCU1xtyRFgRHjWJTiFdC3PTjB8")
Dialed remote peer: "/ip4/127.0.0.1/tcp/51574"
Listening on local Address "/ip4/127.0.0.1/tcp/51582"
Listening on local Address "/ip4/192.168.0.100/tcp/51582"
Event received from peer is Event { peer: PeerId("12D3KooWEnxeFEWM3fvcNw8HV1tWojkmTaNVhrQfhPgL2REnngBS"), result: Ok(Pong) }
Event received from peer is Event { peer: PeerId("12D3KooWEnxeFEWM3fvcNw8HV1tWojkmTaNVhrQfhPgL2REnngBS"), result: Ok(Ping { rtt: 192.584µs }) }
Event received from peer is Event { peer: PeerId("12D3KooWEnxeFEWM3fvcNw8HV1tWojkmTaNVhrQfhPgL2REnngBS"), result: Ok(Ping { rtt: 448.375µs }) }
use libp2p::{
futures::StreamExt, // 异步流有关
identity,
mdns::{Mdns, MdnsConfig, MdnsEvent},
swarm::{Swarm, SwarmEvent},
PeerId,
};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let new_key = identity::Keypair::generate_ed25519();
let new_peer_id = PeerId::from(new_key.public());
println!("New Peer ID is: {:?}", new_peer_id);
let transport = libp2p::development_transport(new_key).await?; // 使用密钥对创建传输
let behaviour = Mdns::new(MdnsConfig::default()).await?; // 创建网络行为
let mut swarm = Swarm::new(transport, behaviour, new_peer_id); // 创建Swarm
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
loop {
match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on local Address {:?}", address)
}
SwarmEvent::Behaviour(MdnsEvent::Discovered(peers)) => {
for (peer, addr) in peers {
println!("discovered {} {}", peer, addr);
}
}
SwarmEvent::Behaviour(MdnsEvent::Expired(expired)) => {
for (peer, addr) in expired {
println!("expired {} {}", peer, addr);
}
}
_ => {}
}
}
}
运行
p2p on master [?] is 📦 0.1.0 via 🦀 1.67.1 via 🅒 base took 7m 50.0s
➜ cargo run
Compiling p2p v0.1.0 (/Users/qiaopengjun/rust/p2p)
Finished dev [unoptimized + debuginfo] target(s) in 2.46s
Running `target/debug/p2p`
New Peer ID is: PeerId("12D3KooWNn7jV9VWPf4nH1MtABEjoTL1hp61C5m1SXA91nWyKtfv")
Listening on local Address "/ip4/127.0.0.1/tcp/51717"
Listening on local Address "/ip4/192.168.0.100/tcp/51717"
discovered 12D3KooWNkA9WyKhPBhJ8CNN9P11qgE9r4ZP1VbMyxM3DvUXkRxd /ip4/192.168.0.100/tcp/51718
discovered 12D3KooWNkA9WyKhPBhJ8CNN9P11qgE9r4ZP1VbMyxM3DvUXkRxd /ip4/127.0.0.1/tcp/51718
discovered 12D3KooWG9pdAXdJXQKF3KAMLfJVCbXcoxWzkQWFym3sCynUxsrF /ip4/192.168.0.100/tcp/51721
discovered 12D3KooWG9pdAXdJXQKF3KAMLfJVCbXcoxWzkQWFym3sCynUxsrF /ip4/127.0.0.1/tcp/51721
p2p on master [?] is 📦 0.1.0 via 🦀 1.67.1 via 🅒 base took 7m 10.2s
➜ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.15s
Running `target/debug/p2p`
New Peer ID is: PeerId("12D3KooWNkA9WyKhPBhJ8CNN9P11qgE9r4ZP1VbMyxM3DvUXkRxd")
Listening on local Address "/ip4/127.0.0.1/tcp/51718"
Listening on local Address "/ip4/192.168.0.100/tcp/51718"
discovered 12D3KooWNn7jV9VWPf4nH1MtABEjoTL1hp61C5m1SXA91nWyKtfv /ip4/192.168.0.100/tcp/51717
discovered 12D3KooWNn7jV9VWPf4nH1MtABEjoTL1hp61C5m1SXA91nWyKtfv /ip4/127.0.0.1/tcp/51717
discovered 12D3KooWG9pdAXdJXQKF3KAMLfJVCbXcoxWzkQWFym3sCynUxsrF /ip4/192.168.0.100/tcp/51721
discovered 12D3KooWG9pdAXdJXQKF3KAMLfJVCbXcoxWzkQWFym3sCynUxsrF /ip4/127.0.0.1/tcp/51721
p2p on master [?] is 📦 0.1.0 via 🦀 1.67.1 via 🅒 base
➜ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.16s
Running `target/debug/p2p`
New Peer ID is: PeerId("12D3KooWG9pdAXdJXQKF3KAMLfJVCbXcoxWzkQWFym3sCynUxsrF")
Listening on local Address "/ip4/127.0.0.1/tcp/51721"
Listening on local Address "/ip4/192.168.0.100/tcp/51721"
discovered 12D3KooWNkA9WyKhPBhJ8CNN9P11qgE9r4ZP1VbMyxM3DvUXkRxd /ip4/192.168.0.100/tcp/51718
discovered 12D3KooWNkA9WyKhPBhJ8CNN9P11qgE9r4ZP1VbMyxM3DvUXkRxd /ip4/127.0.0.1/tcp/51718
discovered 12D3KooWNn7jV9VWPf4nH1MtABEjoTL1hp61C5m1SXA91nWyKtfv /ip4/192.168.0.100/tcp/51717
discovered 12D3KooWNn7jV9VWPf4nH1MtABEjoTL1hp61C5m1SXA91nWyKtfv /ip4/127.0.0.1/tcp/51717
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!