data_transfer/
data-transfer.rs

1use bytes::Bytes;
2use noq::Connection;
3
4fn main() {}
5
6#[allow(dead_code, unused_variables)] // Included in `data-transfer.md`
7async fn open_bidirectional_stream(connection: Connection) -> anyhow::Result<()> {
8    let (mut send, mut recv) = connection.open_bi().await?;
9    send.write_all(b"test").await?;
10    send.finish()?;
11    let received = recv.read_to_end(10).await?;
12    Ok(())
13}
14
15#[allow(dead_code)] // Included in `data-transfer.md`
16async fn receive_bidirectional_stream(connection: Connection) -> anyhow::Result<()> {
17    while let Ok((mut send, mut recv)) = connection.accept_bi().await {
18        // Because it is a bidirectional stream, we can both send and receive.
19        println!("request: {:?}", recv.read_to_end(50).await?);
20        send.write_all(b"response").await?;
21        send.finish()?;
22    }
23    Ok(())
24}
25
26#[allow(dead_code)] // Included in `data-transfer.md`
27async fn open_unidirectional_stream(connection: Connection) -> anyhow::Result<()> {
28    let mut send = connection.open_uni().await?;
29    send.write_all(b"test").await?;
30    send.finish()?;
31    Ok(())
32}
33
34#[allow(dead_code)] // Included in `data-transfer.md`
35async fn receive_unidirectional_stream(connection: Connection) -> anyhow::Result<()> {
36    while let Ok(mut recv) = connection.accept_uni().await {
37        // Because it is a unidirectional stream, we can only receive not send back.
38        println!("{:?}", recv.read_to_end(50).await?);
39    }
40    Ok(())
41}
42
43#[allow(dead_code)] // Included in `data-transfer.md`
44async fn send_unreliable(connection: Connection) -> anyhow::Result<()> {
45    connection.send_datagram(Bytes::from(&b"test"[..]))?;
46    Ok(())
47}
48
49#[allow(dead_code)] // Included in `data-transfer.md`
50async fn receive_datagram(connection: Connection) -> anyhow::Result<()> {
51    while let Ok(received_bytes) = connection.read_datagram().await {
52        // Because it is a unidirectional stream, we can only receive not send back.
53        println!("request: {:?}", received_bytes);
54    }
55    Ok(())
56}