当前位置:网站首页>Rust P2P网络应用实战-1 P2P网络核心概念及Ping程序
Rust P2P网络应用实战-1 P2P网络核心概念及Ping程序
2022-07-29 15:26:00 【InfoQ】
P2P网络

传输协议
节点标识
安全规则
节点路由
消息
流多路复用
libp2p
PING
master:p2p Justin$ cargo new libp2p-learn
Created binary (application) `libp2p-learn` package
master:p2p Justin$ cd libp2p-learn/
master:libp2p-learn Justin$ code .
[dependencies]
libp2p = "0.46"
tokio = { version = "1.19", features = ["full"] }
use std::error::Error;
use libp2p::{
futures::StreamExt,
identity,
ping::{Ping, PingConfig},
swarm::SwarmEvent,
Multiaddr, PeerId, Swarm,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// 生成密钥对
let key_pair = identity::Keypair::generate_ed25519();
// 基于密钥对的公钥,生成节点唯一标识peerId
let peer_id = PeerId::from(key_pair.public());
println!("节点ID: {peer_id}");
// 声明Ping网络行为
let behaviour = Ping::new(PingConfig::new().with_keep_alive(true));
// 传输
let transport = libp2p::development_transport(key_pair).await?;
// 网络管理模块
let mut swarm = Swarm::new(transport, behaviour, peer_id);
// 在节点随机开启一个端口监听
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!("链接远程节点: {remote_peer}");
}
loop {
// 匹配网络事件
match swarm.select_next_some().await {
// 监听事件
SwarmEvent::NewListenAddr { address, .. } => {
println!("本地监听地址: {address}");
}
// 网络行为事件
SwarmEvent::Behaviour(event) => println!("{:?}", event),
_ => {}
}
}
}
- 网络行为Behaviour:传输(transport)定义如何在网络中发送字节流,而网络行为定义发送什么样的字节流,在这里我们发送ping/pong消息。
- 网络管理模块Swarm:用于管理节点之间的所有活跃连接和挂起连接,并管理所有已打开的子流状态。Swarm是通过传输、网络行为和节点PeerId来创建。
- 节点地址:/ip4/0.0.0.0/tcp/0,表示在本机所有ip地址上,开一个随机的Tcp端口进行监听。
cargo run --bin ping
master:libp2p-learn Justin$ cargo run --bin ping
Compiling libp2p-learn v0.1.0 (/Users/Justin/workspace_rust_exercise/network-study/p2p/libp2p-learn)
Finished dev [unoptimized + debuginfo] target(s) in 8.65s
Running `target/debug/ping`
节点ID: 12D3KooWR7H9SwB2yiFBKvzcVGFdpeKmuFG9qDTBTvuuuDarASST
本地监听地址: /ip4/127.0.0.1/tcp/58645
cargo run --bin ping /ip4/127.0.0.1/tcp/58645
master:libp2p-learn Justin$ cargo run --bin ping /ip4/127.0.0.1/tcp/58645
Finished dev [unoptimized + debuginfo] target(s) in 0.36s
Running `target/debug/ping /ip4/127.0.0.1/tcp/58645`
节点ID: 12D3KooWCUFTHNMJrR1p8vkFEFFYm4J8iPA1Wh6x2Dya5qmU1xdL
链接远程节点: /ip4/127.0.0.1/tcp/58645
本地监听地址: /ip4/127.0.0.1/tcp/58727
Event { peer: PeerId("12D3KooWR7H9SwB2yiFBKvzcVGFdpeKmuFG9qDTBTvuuuDarASST"), result: Ok(Pong) }
Event { peer: PeerId("12D3KooWR7H9SwB2yiFBKvzcVGFdpeKmuFG9qDTBTvuuuDarASST"), result: Ok(Ping { rtt: 1.234008ms }) }
边栏推荐
- 【GoLang】Sync lock
- 多线程顺序运行的 4 种方法,面试随便问!
- [MySQL] 运算符
- 分析Nacos配置及源码
- UFLO:5、启动任务并自动完成第一个人工任务
- 小学生学程序---百变服装
- See you in shenzhen!Cloud native to accelerate the application building special: see cloud native FinOps, SRE, high-performance computing scenario best practices
- The future trend of the conversation
- 理解 Web3 的权威指南
- 走高质量、可持续的保障亿万家庭之路 水滴公司发布2020·2021ESG报告
猜你喜欢
Shell脚本编程-运算
一文读懂Elephant Swap,为何为ePLATO带来如此高的溢价?
Qt combat | how to access the USB device information?
qt vs2015中无法打开源文件“QtWidgets”的解决方案
属性动画(Property Animation) 、 Butterknife黄油刀的基本使用
ES6 从入门到精通 # 11:Map 数据类型
[Designers must learn] Lighting skills of Enscape in SketchUp
See you in shenzhen!Cloud native to accelerate the application building special: see cloud native FinOps, SRE, high-performance computing scenario best practices
打卡广汽本田喜悦安全驾驶中心,体验最刁钻的场地训练
Altair SimSolid complex assembly meshless rapid structure simulation online seminars
随机推荐
如果不知道这4种缓存模式,敢说懂缓存吗?
I/O Code Practice
File management: logical structure
gateway基本使用
深圳见!云原生加速应用构建专场:来看云原生 FinOps、SRE、高性能计算场景最佳实践
ES6 从入门到精通 # 10:Set 集合数据类型
BGP federation experiment
数据库管控平台-awr报告采集(mysql/oracle)
文件管理:文件的逻辑结构
【微信小程序】组件使用及属性参考
[Designers must learn] Lighting skills of Enscape in SketchUp
Linux环境 redis完整配置及启动命令
我把小程序搬到了自有App中,开发效率提升了5倍
金九银十必备 快来看看你还缺啥
AI全流程开发难题破解之钥
KDD'22博士论文奖:清华裘捷中成亚洲高校首位获得者,斯坦福Rex Ying获WINNER奖
进入中国27年,又一美妆巨头要离场
求连续90日每日的用户留存率 -- 全网唯一
File management: the physical structure of files
Jenkins持续集成与自动化部署系统安装配置