]> git.lizzy.rs Git - dragonblocks-rs.git/blob - src/server/remote_client.rs
Logging
[dragonblocks-rs.git] / src / server / remote_client.rs
1 use super::pkts::*;
2 use super::ServerData;
3 use crate::pkt;
4 use crate::Quit;
5 use connect::{ConnectDatagram, ConnectionReader, ConnectionWriter, StreamExt};
6 use log::*;
7 use std::sync::Weak;
8 use tokio::sync::Mutex as AsyncMutex;
9
10 pub type ClientId = u64;
11
12 pub struct Client {
13     pub id: ClientId,
14     pub conn: AsyncMutex<ConnectionWriter>,
15     pub server: Weak<ServerData>,
16     pub quit: Quit,
17 }
18
19 impl Client {
20     async fn login(&self, pkt: &Login) {
21         info!(
22             "Client {id}: logged in {name} {pwd}",
23             id = self.id,
24             name = pkt.name,
25             pwd = pkt.pwd
26         );
27     }
28
29     async fn handle(&self, msg: &ConnectDatagram) {
30         match msg.recipient() {
31                         LOGIN if let Some(pkt) = pkt::get::<Login>(msg) => self.login(&pkt).await,
32                         _ => warn!("Client {id}: Invalid packet with recipient {rep}",
33                                 id = self.id, rep = msg.recipient()),
34                 }
35     }
36
37     pub async fn run(&self, mut reader: ConnectionReader) {
38         let mut quit = self.quit.subscribe();
39
40         loop {
41             tokio::select! {
42                 msg = reader.next() => match msg {
43                     Some(msg) => self.handle(&msg).await,
44                     None => {
45                         trace!("Client {id}: Closed connection", id = self.id);
46                         break;
47                     }
48                 },
49                 _ = quit.recv() => {
50                     trace!("Client {id}: Quit signal received", id = self.id);
51                     break;
52                 },
53                 else => unreachable!("Quit channel broke"),
54             }
55         }
56
57         if let Some(server) = self.server.upgrade() {
58             server.clients_by_id.write().unwrap().remove(&self.id);
59             trace!("Client {id}: Removed from clients", id = self.id);
60         }
61
62         info!("Client {id}: Disconnected", id = self.id);
63     }
64 }