kubi/kubi-udp/src/client.rs

70 lines
1.8 KiB
Rust
Raw Normal View History

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:54:12 -06:00
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClientStatus {
Disconnected,
Connecting,
Connected,
}
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:54:12 -06:00
status: ClientStatus,
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:54:12 -06:00
pub fn new(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)?;
2023-02-01 18:54:12 -06:00
Ok(Self {
2023-02-01 18:40:48 -06:00
addr,
config,
2023-01-31 20:16:23 -06:00
socket,
2023-02-01 18:54:12 -06:00
status: ClientStatus::Disconnected,
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:54:12 -06:00
})
}
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(())
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-02-01 18:54:12 -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
}