DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: initial-tcp-experimentation emerwen/emerwen-master/src/server.rs -rw-r--r-- 1.4 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
use emerwen_protocol::ProtocolActorHandle;
use tokio::net::TcpListener;
use tracing::info;

pub struct Server {
    addr: String,
}

impl Server {
    pub fn new(addr: impl Into<String>) -> Server {
        Server { addr: addr.into() }
    }

    pub async fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        let listener = TcpListener::bind(&self.addr).await?;
        info!("Server listening on {}", self.addr);

        loop {
            let (socket, addr) = listener.accept().await?;

            info!("Client '{}' connected", addr);

            let handle_read = ProtocolActorHandle::new(socket);
            let handle_write = handle_read.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
                }
            });

            tokio::task::spawn(async move {
                let handle = handle_write;
                loop {
                    // read some channel that comes passed from main to this server struct
                    // and send messages yeah.
                    //let message = handle.send_message(Message).await;
                }
            });
        }
    }
}