6 releases

new 0.1.5 May 14, 2024
0.1.4 Mar 21, 2024
0.1.2 Feb 5, 2024
0.1.1 Jan 22, 2024
0.1.0 Dec 4, 2023

#2078 in Network programming

Download history 7/week @ 2024-01-16 2/week @ 2024-01-23 12/week @ 2024-01-30 8/week @ 2024-02-06 6/week @ 2024-02-13 115/week @ 2024-02-20 60/week @ 2024-02-27 1/week @ 2024-03-05 10/week @ 2024-03-12 262/week @ 2024-03-19 6/week @ 2024-03-26 29/week @ 2024-04-02 21/week @ 2024-04-09 21/week @ 2024-04-16 13/week @ 2024-04-23 19/week @ 2024-04-30

80 downloads per month

Apache-2.0 OR MIT

35KB
965 lines

P2P

A p2p networking library

Example

const ALPN: &[u8] = b"/p2p/ping/1";

#[derive(Debug, Deserialize, Serialize)]
pub struct Ping(u16);

#[derive(Debug, Deserialize, Serialize)]
pub struct Pong(u16);

pub struct PingPong;

impl Protocol for PingPong {
    const ID: u16 = 0;
    const REQ_BUF: usize = 1024;
    const RES_BUF: usize = 1024;
    type Request = Ping;
    type Response = Pong;
}

impl RequestHandler<Self> for PingPong {
    fn request(
        &self,
        _peer_id: PeerId,
        request: <Self as Protocol>::Request,
        response: oneshot::Sender<<Self as Protocol>::Response>,
    ) -> Result<()> {
        response
            .send(Pong(request.0))
            .map_err(|_| anyhow::anyhow!("response channel closed"))?;
        Ok(())
    }
}

let mut builder = ProtocolHandler::builder();
builder.register_request_handler(PingPong);
let handler = builder.build();

let mut builder = Endpoint::builder(ALPN.to_vec());
builder.handler(handler);
let endpoint = builder.build().await?;
let pong = endpoint.request::<PingPong>(&peer, &Ping(42)).await?;
assert_eq!(pong.0, 42);

License

Apache-2.0 + MIT

Dependencies

~42–81MB
~1.5M SLoC