Module communication::behaviour[][src]

P2PNetworkBehaviour

This module implements the P2PNetworkBehaviour that creates a [ExpandedSwarm] as entry point for all communication. It provides an interface to send request/ responses to other peers, manage the known peers, and poll for incoming events.

Example

The below example initiates, and polls from a Swarm, and reponds to each incoming Ping with a Pong.

use async_std::task;
use communication::behaviour::{BehaviourConfig, P2PEvent, P2PNetworkBehaviour, P2PReqResEvent};
use core::ops::Deref;
use libp2p::identity::Keypair;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Request {
    Ping,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Response {
    Pong,
}

task::block_on(async {
    let local_keys = Keypair::generate_ed25519();
    let config = BehaviourConfig::default();
    let mut swarm = P2PNetworkBehaviour::<Request, Response>::init_swarm(local_keys, config)
        .await
        .expect("Init swarm failed.");
    loop {
        if let P2PEvent::RequestResponse(boxed_event) = swarm.next().await {
            if let P2PReqResEvent::Req {
                peer_id,
                request_id,
                request: Request::Ping,
            } = boxed_event.deref().clone()
            {
                let res = swarm.behaviour_mut().send_response(&request_id, Response::Pong);
                if res.is_err() {
                    break;
                }
            }
        }
    }
});

Structs

BehaviourConfig

Configuration for initiating the P2PNetworkBehaviour.

P2PIdentifyInfo

Information of a peer sent in Identify protocol responses.

P2PNetworkBehaviour

The P2PNetworkBehaviour determines the behaviour of the p2p-network. It combines the following protocols from libp2p

Enums

BehaviourError

Error upon creating a new P2PNetworkBehaviour

P2PEvent

Event that was emitted by one of the protocols of the P2PNetworkBehaviour

P2PIdentifyEvent

Event emitted by the Identify behaviour.

P2PInboundFailure

Possible failures occurring in the context of receiving an inbound request and sending a response.

P2PMdnsEvent

Event that can be produced by the Mdns behaviour.

P2POutboundFailure

Possible failures occurring in the context of sending an outbound request and receiving the response.

P2PProtocolsHandlerUpgrErr

Error that can happen on an outbound substream opening attempt.

P2PReqResEvent

Event emitted by the RequestResponse behaviour.

Traits

MessageEvent

Trait for the generic Request and Response types