- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在寻找一种利用mDNS,floodsub和kademlia DHT的网络行为。到目前为止,我已经使所有这些服务都可以使用,但是还不能将这些服务的响应用于有意义的事情。
理想情况下,我将能够将来自行为过程事件的数据(例如将为Kad DHT实现的事件)输送到主Swarm poll
循环中。例如,在我的情况下,我对表示通过sled
数据库保留在磁盘上的图形的结构的引用。该结构的所有权存在于轮询群的方法中。收到KademliaEvent
后,我将如何更新此图表(例如添加条目)?
我尝试过的解决方案:
ClientBehavior
结构的位置,这样我就可以通过self.my_data_structure.add(result);
KademliaEvent
方法中的inject_event
#[derive(NetworkBehaviour)]
根本不喜欢这个Graph
只是一个结构,不会发出任何事件/实现NetworkBehaviour
Context
结构,该结构由derive
的NetworkBehaviour
组成,可用于在轮询方法和相应的inject_event
方法之间来回传递响应#[derive(NetworkBehaviour)]
不能与Arc
s/Mutex
es /// A network behavior describing a client connected to a pub-sub compatible,
/// optionally mDNS-compatible network. Such a "behavior" may be implemented for
/// any libp2p transport, but any transport used with this behavior must implement
/// asynchronous reading & writing capabilities.
#[derive(NetworkBehaviour)]
pub struct ClientBehavior<TSubstream: AsyncRead + AsyncWrite + Send + Unpin + 'static> {
/// Some pubsub mechanism bound to the above transport
pub floodsub: Floodsub<TSubstream>,
/// Some mDNS service bound to the above transport
pub mdns: Mdns<TSubstream>,
/// Allow for the client to do some external discovery on the global network through a KAD DHT
pub kad_dht: Kademlia<TSubstream, MemoryStore>,
}
NetworkBehaviourEventProceess
实现如下所示:
impl<TSubstream: AsyncRead + AsyncWrite + Send + Unpin + 'static>
NetworkBehaviourEventProcess<KademliaEvent> for ClientBehavior<TSubstream>
{
fn inject_event(&mut self, event: KademliaEvent) {
// Some behavior logic, nothing special, really, just a bunch of matches
// NOTE: this is when I'd want to update the `Graph`, since KademliaEvent will contain data that I need to put in the `Graph` instance
}
}
Swarm
和
ClientBehavior
:
// Initialize a new behavior for a client that we will generate in the not-so-distant future with the given peerId, alongside
// an mDNS service handler as well as a floodsub instance targeted at the given peer
let mut behavior = ClientBehavior {
floodsub: Floodsub::new(self.peer_id.clone()),
mdns: Mdns::new().await?,
kad_dht: Kademlia::new(self.peer_id.clone(), store),
};
// Iterate through bootstrap addresses
for bootstrap_peer in bootstrap_addresses {
// NOTE: add_address is a method that isn't provided by #[derive(NetworkBehaviour)].
// It's just a helper method I wrote that adds the peer to the Floodsub & DHT views.
behavior.add_address(&bootstrap_peer.0, bootstrap_peer.1); // Add the bootstrap peer to the DHT
}
// Bootstrap the behavior's DHT
behavior.kad_dht.bootstrap();
// Note: here, `self` is a reference to a configuration struct holding a peer ID, and a keypair
let mut swarm = Swarm::new(
libp2p::build_tcp_ws_secio_mplex_yamux(self.keypair.clone())?,
behavior,
self.peer_id.clone(),
); // Initialize a swarm
// NOTE: Here, `self` has ownership of the aforementioned `Graph` instance. I'd like to update this
// instance from this block, or from the ClientBehavior itself--as long as I'm able to update it once a `KademliaEvent` is received.
// Try to get the address we'll listen on
if let Ok(addr) = format!("/ip4/0.0.0.0/tcp/{}", port).parse::<Multiaddr>() {
// Try to tell the swarm to listen on this address, return an error if this doesn't work
if let Err(e) = Swarm::listen_on(&mut swarm, addr.clone()) {
// Convert the addr err into an io error
let e: std::io::Error = io::ErrorKind::AddrNotAvailable.into();
// Return an error
return Err(e.into());
};
// Fetch the hash of the first transaction in the DAG from the network
swarm
.kad_dht
.get_record(&Key::new(&sync::ROOT_TRANSACTION_KEY), Quorum::Majority);
loop {
// Poll the swarm
match swarm.next_event().await {
// NOTE: Initially, I was under the impression that I would be able to intercept
// events from the ClientBehavior here. Yet, the below info! call is never reached.
// This remains the case in libp2p example code that I have experimented with.
SwarmEvent::Behaviour(e) => info!("idk: {:?}", e),
_ => debug!("Some other event; this is handled specifically in the actual codebase, but for this question, all I really care about is the above behavior event."),
};
}
}
NetworkBehaviour
?
最佳答案
您的问题有点晚了,但这也许会有所帮助:
Moving ownership of the data structure I want to update to the ClientBehavior struct so I can just self.my_data_structure.add(result); from the KademliaEvent inject_event method
- #[derive(NetworkBehaviour)] does NOT like this at all
- Graph is just a struct, and doesn't emit any events / implement NetworkBehaviour
#[behaviour(ignore)] can be added on a struct field to disable generation of delegation to the fields which do not implement NetworkBehaviour.
Poll::Ready(GenerateEvent(TOut))
)发出自定义事件,然后您可以监听该事件通过另一个NetworkBehaviourEventProcess impl获取对应的结构,然后应修改该结构。
poll()
中传播该事件队列的方法,您可以在ClientBehaviour中有一个类似的队列(标记为
behaviour(ignore)]
),追加到队列中,以
poll()
发出事件,并在调用代码/等待中捕获该特定事件循环以某种方式?
关于rust - 如何从派生的NetworkBehaviour发出SwarmEvent::Behaviour?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812399/
编辑备注 由于 Rust(版本:1.42)仍然没有稳定的 ABI ,推荐使用extern (目前相当于extern "C"(将来可能会改变))否则,可能需要重新编译库。 This article解释如
词法分析器/解析器文件位于 here非常大,我不确定它是否适合只检索 Rust 函数列表。也许我自己编写/使用另一个库是更好的选择? 最终目标是创建一种执行管理器。为了上下文化,它将能够读取包装在函数
我试图在 Rust 中展平 Enum 的向量,但我遇到了一些问题: enum Foo { A(i32), B(i32, i32), } fn main() { let vf =
我正在 64 位模式下运行的 Raspberry Pi 3 上使用 Rust 进行裸机编程。我已经实现了一个自旋锁,如下所示: use core::{sync::atomic::{AtomicBool
我无法理解以下示例是如何从 this code 中提炼出来的, 编译: trait A: B {} trait B {} impl B for T where T: A {} struct Foo;
在我写了一些代码和阅读了一些文章之后,我对 Rust 中的移动语义有点困惑,我认为值移动后,它应该被释放,内存应该是无效的。所以我尝试写一些代码来作证。 第一个例子 #[derive(Debug)]
https://doc.rust-lang.org/reference/types/closure.html#capture-modes struct SetVec { set: HashSe
考虑 const-generic 数据结构的经典示例:方矩阵。 struct Matrix { inner: [[T; N]; N] } 我想返回一个结构体,其 const 参数是动态定义的:
以下代码无法编译,因为 x在移动之后使用(因为 x 具有类型 &mut u8 ,它没有实现 Copy 特性) fn main() { let mut a: u8 = 1; let x:
我在玩 Rust,发现了下面的例子: fn main() { let mut x = [3, 4, 5].to_vec(); x; println!("{:?}", x); }
假设一个 Rust 2018 宏定义了一个 async里面的功能。它将使用的语法与 Rust 2015 不兼容。因此,如果您使用 2015 版编译您的 crate,那么宏中的扩展代码不会与它冲突吗?
假设我有一些 Foo 的自定义集合s: struct Bar {} struct Foo { bar: Bar } struct SubList { contents: Vec, }
代码如下: fn inner(x:&'a i32, _y:&'b i32) -> &'b i32 { x } fn main() { let a = 1; { let b
在lifetime_things的定义中,'b的生命周期比'a长,但实际上当我调用这个函数时,x1比y1长,但是这样可以编译成功: //here you could see 'b:'a means
我正在尝试检索 FLTK-RS Widget 周围的 Arc Mutex 包装器的内部值: pub struct ArcWidget(Arc>); impl ArcWidget{ pub
如下代码所示,我想封装一个定时函数,返回一个闭包的结果和执行时间。 use tap::prelude::Pipe; use std::time::{Instant, Duration}; pub fn
我想实现自己的通用容器,这是我正在使用的特征的片段: pub trait MyVec where Self: Default + Clone + IntoIterator, Self:
所需代码: 注释掉的块可以编译并工作,但是我想从嵌套的匹配样式转变为更简洁的函数链 async fn ws_req_resp(msg: String, conn: PgConn) -> Result>
我正在尝试编写一些代码,该代码将生成具有随机值的随机结构。对于结构,我具有以下特征和帮助程序宏: use rand::{thread_rng, Rng}; use std::fmt; pub trai
我有一个带有函数成员的结构: struct Foo { fun: Box, } type FooI = Foo; 这不起作用: error[E0106]: missing lifetime s
我是一名优秀的程序员,十分优秀!