]> git.lizzy.rs Git - dragonblocks-rs.git/blob - src/client.rs
Logging
[dragonblocks-rs.git] / src / client.rs
1 use crate::pkt;
2 use crate::quit::Quit;
3 use crate::server::pkts as server_bound;
4 use connect::{ConnectDatagram, Connection, ConnectionReader, ConnectionWriter, StreamExt};
5 use log::*;
6 use tokio::sync::Mutex as AsyncMutex;
7
8 pub struct Client {
9     pub conn: AsyncMutex<ConnectionWriter>,
10     quit: Quit,
11 }
12
13 impl Client {
14     pub async fn run(addr: &str, quit: Quit) {
15         let (reader, writer) = Connection::tcp_client(addr).await.unwrap().split();
16
17         Self {
18             conn: AsyncMutex::new(writer),
19             quit,
20         }
21         .run_loop(reader)
22         .await;
23     }
24
25     async fn handle(&self, msg: &ConnectDatagram) {
26         println!("{}", msg.recipient());
27     }
28
29     async fn run_loop(self, mut reader: ConnectionReader) {
30         let mut quit = self.quit.subscribe();
31
32         pkt::put(
33             &self.conn,
34             server_bound::LOGIN,
35             &server_bound::Login {
36                 name: "player".into(),
37                 pwd: "password123".into(),
38             },
39         )
40         .await;
41
42         loop {
43             tokio::select! {
44                 msg = reader.next() => match msg {
45                     Some(msg) => self.handle(&msg).await,
46                     None => {
47                         trace!("Server closed connection");
48                         break;
49                     }
50                 },
51                 _ = quit.recv() => {
52                     trace!("Quit signal received");
53                     break;
54                 },
55                 else => unreachable!("Quit channel broke"),
56             }
57         }
58
59         info!("Disconnected");
60     }
61 }