aboutsummaryrefslogtreecommitdiff
path: root/net/examples/tcp_codec.rs
blob: 93deaae87bca7cf5993b60aba8ea2dd8d32e2573 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use std::time::Duration;

use karyon_core::async_util::sleep;

use karyon_net::{
    codec::{Codec, Decoder, Encoder},
    tcp, ConnListener, Connection, Endpoint, Result,
};

#[derive(Clone)]
struct NewLineCodec {}

impl Codec for NewLineCodec {
    type Item = String;
}

impl Encoder for NewLineCodec {
    type EnItem = String;
    fn encode(&self, src: &Self::EnItem, dst: &mut [u8]) -> Result<usize> {
        dst[..src.len()].copy_from_slice(src.as_bytes());
        Ok(src.len())
    }
}

impl Decoder for NewLineCodec {
    type DeItem = String;
    fn decode(&self, src: &mut [u8]) -> Result<Option<(usize, Self::DeItem)>> {
        match src.iter().position(|&b| b == b'\n') {
            Some(i) => Ok(Some((i + 1, String::from_utf8(src[..i].to_vec()).unwrap()))),
            None => Ok(None),
        }
    }
}

fn main() {
    smol::block_on(async {
        let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();

        let config = tcp::TcpConfig::default();

        let listener = tcp::listen(&endpoint, config.clone(), NewLineCodec {})
            .await
            .unwrap();
        smol::spawn(async move {
            if let Ok(conn) = listener.accept().await {
                loop {
                    let msg = conn.recv().await.unwrap();
                    println!("Receive a message: {:?}", msg);
                }
            };
        })
        .detach();

        let conn = tcp::dial(&endpoint, config, NewLineCodec {}).await.unwrap();
        conn.send("hello".to_string()).await.unwrap();
        conn.send(" world\n".to_string()).await.unwrap();
        sleep(Duration::from_secs(1)).await;
    });
}