2023-01-31 20:16:23 -06:00
|
|
|
use std::{
|
|
|
|
net::{UdpSocket, SocketAddr},
|
2023-02-01 18:40:48 -06:00
|
|
|
marker::PhantomData, time::Instant
|
2023-01-31 20:16:23 -06:00
|
|
|
};
|
|
|
|
use bincode::{Encode, Decode};
|
|
|
|
use crate::{BINCODE_CONFIG, packet::ClientPacket};
|
|
|
|
|
2023-02-01 18:40:48 -06:00
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
|
|
pub struct ClientConfig {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2023-01-31 20:24:06 -06:00
|
|
|
pub struct Client<S, R> where S: Encode + Decode, R: Encode + Decode {
|
2023-02-01 18:40:48 -06:00
|
|
|
addr: SocketAddr,
|
|
|
|
config: ClientConfig,
|
2023-01-31 20:16:23 -06:00
|
|
|
socket: UdpSocket,
|
2023-02-01 18:40:48 -06:00
|
|
|
last_heartbeat: Instant,
|
2023-01-31 20:25:12 -06:00
|
|
|
_s: PhantomData<*const S>,
|
|
|
|
_r: PhantomData<*const R>,
|
2023-01-31 20:16:23 -06:00
|
|
|
}
|
2023-01-31 20:24:06 -06:00
|
|
|
impl<S, R> Client<S, R> where S: Encode + Decode, R: Encode + Decode {
|
2023-02-01 18:40:48 -06:00
|
|
|
pub fn connect(addr: SocketAddr, config: ClientConfig) -> anyhow::Result<Self> {
|
2023-01-31 20:16:23 -06:00
|
|
|
let bind_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
|
|
|
|
let socket = UdpSocket::bind(bind_addr)?;
|
|
|
|
socket.set_nonblocking(true)?;
|
|
|
|
socket.connect(addr)?;
|
2023-01-31 20:24:06 -06:00
|
|
|
let client = Self {
|
2023-02-01 18:40:48 -06:00
|
|
|
addr,
|
|
|
|
config,
|
2023-01-31 20:16:23 -06:00
|
|
|
socket,
|
2023-02-01 18:40:48 -06:00
|
|
|
last_heartbeat: Instant::now(),
|
2023-01-31 20:24:06 -06:00
|
|
|
_s: PhantomData,
|
|
|
|
_r: PhantomData,
|
|
|
|
};
|
2023-02-01 18:40:48 -06:00
|
|
|
client.send_raw_packet(&ClientPacket::Connect)?;
|
2023-01-31 20:24:06 -06:00
|
|
|
Ok(client)
|
2023-01-31 20:16:23 -06:00
|
|
|
}
|
2023-02-01 18:40:48 -06:00
|
|
|
fn send_raw_packet(&self, packet: &ClientPacket<S>) -> anyhow::Result<()> {
|
2023-01-31 20:16:23 -06:00
|
|
|
let bytes = bincode::encode_to_vec(packet, BINCODE_CONFIG)?;
|
|
|
|
self.socket.send(&bytes)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
2023-01-31 20:24:06 -06:00
|
|
|
pub fn send_message(&self, message: S) -> anyhow::Result<()> {
|
2023-02-01 18:40:48 -06:00
|
|
|
self.send_raw_packet(&ClientPacket::Data(message))?;
|
2023-01-31 20:16:23 -06:00
|
|
|
Ok(())
|
|
|
|
}
|
2023-01-31 20:24:06 -06:00
|
|
|
pub fn disconnect(self) -> anyhow::Result<()> {
|
2023-02-01 18:40:48 -06:00
|
|
|
self.send_raw_packet(&ClientPacket::Disconnect)?;
|
2023-01-31 20:16:23 -06:00
|
|
|
Ok(())
|
|
|
|
}
|
2023-02-01 18:40:48 -06:00
|
|
|
pub fn update(&mut self) {
|
|
|
|
|
|
|
|
}
|
2023-01-31 20:16:23 -06:00
|
|
|
}
|