3 unstable releases

0.2.0-alpha Aug 9, 2024
0.1.0-alpha.1 May 20, 2024
0.1.0-alpha Jan 17, 2024

#1562 in Asynchronous

Download history 634/week @ 2024-08-16 1370/week @ 2024-08-23 1499/week @ 2024-08-30 1130/week @ 2024-09-06 1170/week @ 2024-09-13 1356/week @ 2024-09-20 1665/week @ 2024-09-27 925/week @ 2024-10-04 722/week @ 2024-10-11 997/week @ 2024-10-18 926/week @ 2024-10-25 3049/week @ 2024-11-01 7941/week @ 2024-11-08 7535/week @ 2024-11-15 11915/week @ 2024-11-22 11690/week @ 2024-11-29

41,121 downloads per month
Used in 4 crates

MIT license

755KB
15K SLoC

Generic (stream) protocols

This module provides a generic NetworkBehaviour for stream-oriented protocols. Streams are the fundamental primitive of libp2p and all other protocols are implemented using streams. In contrast to other NetworkBehaviours, this module takes a different design approach. All interaction happens through a Control that can be obtained via Behaviour::new_control. Controls can be cloned and thus shared across your application.

Inbound

To accept streams for a particular StreamProtocol using this module, use Control::accept:

Example

# fn main() {
# use libp2p_swarm::{Swarm, StreamProtocol};
# use libp2p_stream as stream;
# use futures::StreamExt as _;
let mut swarm: Swarm<stream::Behaviour> = todo!();

let mut control = swarm.behaviour().new_control();
let mut incoming = control.accept(StreamProtocol::new("/my-protocol")).unwrap();

let handler_future = async move {
    while let Some((peer, stream)) = incoming.next().await {
        // Execute your protocol using `stream`.
    }
};
# }

Resource management

Control::accept returns you an instance of IncomingStreams. This struct implements Stream and like other streams, is lazy. You must continuously poll it to make progress. In the example above, this taken care of by using the StreamExt::next helper.

Internally, we will drop streams if your application falls behind in processing these incoming streams, i.e. if whatever loop calls .next() is not fast enough.

Drop

As soon as you drop IncomingStreams, the protocol will be de-registered. Any further attempt by remote peers to open a stream using the provided protocol will result in a negotiation error.

Outbound

To open a new outbound stream for a particular protocol, use Control::open_stream.

Example

# fn main() {
# use libp2p_swarm::{Swarm, StreamProtocol};
# use libp2p_stream as stream;
# use libp2p_identity::PeerId;
let mut swarm: Swarm<stream::Behaviour> = todo!();
let peer_id: PeerId = todo!();

let mut control = swarm.behaviour().new_control();

let protocol_future = async move {
    let stream = control.open_stream(peer_id, StreamProtocol::new("/my-protocol")).await.unwrap();

    // Execute your protocol here using `stream`.
};
# }

Dependencies

~8–15MB
~181K SLoC