DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: 1225af8e42a83251f51013fddcb2f368c108612c emerwen/emerwen-worker/src/client.rs -rw-r--r-- 1.7 KiB
1225af8eJonni Liljamo feat: more experimentation 13 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
use emerwen_protocol::{message::payload::MessagePayload, ProtocolActorHandle};
use tokio::{
    net::TcpStream,
    sync::mpsc::{Receiver, Sender},
};
use tracing::info;

pub enum ClientMessage {
    SendPayload { payload: MessagePayload },
}

pub struct Client {
    addr: String,
    worker_tx: Sender<ClientMessage>,
    payload_rx: Receiver<MessagePayload>,
}

impl Client {
    pub fn new(
        addr: impl Into<String>,
        worker_tx: Sender<ClientMessage>,
        payload_rx: Receiver<MessagePayload>,
    ) -> Client {
        Client {
            addr: addr.into(),
            worker_tx,
            payload_rx,
        }
    }

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

        let handle = ProtocolActorHandle::new(socket);
        let handle_read = handle.clone();

        tokio::task::spawn(async move {
            let handle = handle_read;
            loop {
                let message = handle.read_message().await;

                info!("Received message: {:?}", message);

                // match payload bla bla
                // write something back if appliccable

                // use worker_tx to send data to main worker thread
            }
        });

        info!("before prx");
        while let Some(payload) = self.payload_rx.recv().await {
            info!("prx");
            let _ = handle.send_message(payload).await;
        }
        info!("after prx");

        // read some channel that comes passed from main to this server struct
        // and send messages yeah.
        //let message = handle.send_message(Message).await;

        Ok(())
    }
}