diff --git a/kubi-udp/src/client.rs b/kubi-udp/src/client.rs index 892f6ba..30f3333 100644 --- a/kubi-udp/src/client.rs +++ b/kubi-udp/src/client.rs @@ -5,6 +5,13 @@ use std::{ use bincode::{Encode, Decode}; use crate::{BINCODE_CONFIG, packet::ClientPacket}; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ClientStatus { + Disconnected, + Connecting, + Connected, +} + #[derive(Clone, Copy, Debug)] pub struct ClientConfig { @@ -14,26 +21,34 @@ pub struct Client where S: Encode + Decode, R: Encode + Decode { addr: SocketAddr, config: ClientConfig, socket: UdpSocket, + status: ClientStatus, last_heartbeat: Instant, _s: PhantomData<*const S>, _r: PhantomData<*const R>, } impl Client where S: Encode + Decode, R: Encode + Decode { - pub fn connect(addr: SocketAddr, config: ClientConfig) -> anyhow::Result { + pub fn new(addr: SocketAddr, config: ClientConfig) -> anyhow::Result { let bind_addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); let socket = UdpSocket::bind(bind_addr)?; socket.set_nonblocking(true)?; - socket.connect(addr)?; - let client = Self { + Ok(Self { addr, config, socket, + status: ClientStatus::Disconnected, last_heartbeat: Instant::now(), _s: PhantomData, _r: PhantomData, - }; - client.send_raw_packet(&ClientPacket::Connect)?; - Ok(client) + }) + } + pub fn connect(&mut self) -> anyhow::Result<()> { + if self.status != ClientStatus::Disconnected { + anyhow::bail!("Already {:?}", self.status); + } + self.status = ClientStatus::Connecting; + self.socket.connect(self.addr)?; + self.send_raw_packet(&ClientPacket::Connect)?; + Ok(()) } fn send_raw_packet(&self, packet: &ClientPacket) -> anyhow::Result<()> { let bytes = bincode::encode_to_vec(packet, BINCODE_CONFIG)?; @@ -44,7 +59,7 @@ impl Client where S: Encode + Decode, R: Encode + Decode { self.send_raw_packet(&ClientPacket::Data(message))?; Ok(()) } - pub fn disconnect(self) -> anyhow::Result<()> { + pub fn disconnect(&self) -> anyhow::Result<()> { self.send_raw_packet(&ClientPacket::Disconnect)?; Ok(()) } diff --git a/kubi-udp/src/packet.rs b/kubi-udp/src/packet.rs index 49ca38d..eb3505b 100644 --- a/kubi-udp/src/packet.rs +++ b/kubi-udp/src/packet.rs @@ -3,8 +3,16 @@ use bincode::{Encode, Decode}; #[repr(u8)] #[derive(Encode, Decode)] pub enum ClientPacket where T: Encode + Decode { + Data(T), Connect, Disconnect, Heartbeat, - Data(T) +} + +#[repr(u8)] +#[derive(Encode, Decode)] +pub enum ServerPacket where T: Encode + Decode { + Data(T), + Connected, + Disconnected, }