DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: ef2b830165b22e9bcc235221875b81e359a8bb7d emerwen/emerwen-master/src/main.rs -rw-r--r-- 2.0 KiB
ef2b8301Jonni Liljamo feat: 2nd protocol iteration 15 days ago
                                                                                
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use clap::Parser;
use emerwen_protocol::Message;
use tokio::{io::AsyncWriteExt, net::TcpStream};
use tracing::{debug, info, level_filters::LevelFilter};
use tracing_subscriber::{prelude::*, EnvFilter};

#[derive(Parser)]
#[command(version)]
struct Args {
    /// Enable debug logging
    #[arg(long)]
    debug: bool,
}

#[tokio::main]
async fn main() {
    let args = Args::parse();

    tracing_subscriber::registry()
        .with(
            tracing_subscriber::fmt::layer()
                .with_file(args.debug)
                .with_line_number(args.debug)
                .with_level(true),
        )
        .with(
            EnvFilter::builder()
                .with_default_directive(if args.debug {
                    LevelFilter::DEBUG.into()
                } else {
                    LevelFilter::INFO.into()
                })
                .from_env_lossy(),
        )
        .init();

    info!("Starting emerwen master...");

    debug!("Hello, debug!");

    let mut worker_client = WorkerClient::new("127.0.0.1:8000");
    let _ = worker_client.connect().await;

    let _ = worker_client
        .send_message(&Message::Authentication {
            key: "test".to_owned(),
        })
        .await;
    let _ = worker_client
        .send_message(&Message::Authentication {
            key: "askdas".to_owned(),
        })
        .await;
}

struct WorkerClient {
    addr: String,
    stream: Option<TcpStream>,
}

impl WorkerClient {
    pub fn new(addr: impl Into<String>) -> WorkerClient {
        WorkerClient {
            addr: addr.into(),
            stream: None,
        }
    }

    pub async fn connect(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.stream = Some(TcpStream::connect(&self.addr).await?);
        Ok(())
    }

    pub async fn send_message(
        &mut self,
        message: &Message,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(stream) = &mut self.stream {
            stream.write_all(&message.encode()?).await?;
        }
        Ok(())
    }
}