aboutsummaryrefslogtreecommitdiff
path: root/light-client/src/network.rs
blob: dc6e894fd995c827cadfec4b8b28862d6f4f4d43 (plain)
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
use hurrycurry_protocol::{PacketC, PacketS, BINCODE_CONFIG};
use log::warn;
use std::{collections::VecDeque, net::TcpStream};
use tungstenite::{stream::MaybeTlsStream, Message, WebSocket};

pub struct Network {
    sock: WebSocket<MaybeTlsStream<TcpStream>>,
    queue_in: VecDeque<PacketC>,
    queue_out: VecDeque<PacketS>,
}

impl Network {
    pub fn connect(addr: &str) -> Self {
        let (sock, _resp) = tungstenite::connect(addr).unwrap();
        Self {
            sock,
            queue_in: VecDeque::new(),
            queue_out: VecDeque::new(),
        }
    }
    pub fn poll(&mut self) {
        self.queue_in.extend(match self.sock.read() {
            Ok(Message::Text(packet)) => match serde_json::from_str(&packet) {
                Ok(p) => Some(p),
                Err(e) => {
                    warn!("invalid json packet: {e:?}");
                    None
                }
            },
            Ok(Message::Binary(packet)) => {
                match bincode::decode_from_slice(&packet, BINCODE_CONFIG) {
                    Ok((p, _)) => Some(p),
                    Err(e) => {
                        warn!("invalid bincode packet: {e:?}");
                        None
                    }
                }
            }
            Ok(_) => None,
            Err(e) => {
                warn!("{e:?}");
                None
            }
        });

        for packet in self.queue_out.drain(..) {
            self.sock
                .write(Message::Text(serde_json::to_string(&packet).unwrap()))
                .unwrap();
        }
    }
}