mirror of
https://github.com/griffi-gh/kubi.git
synced 2024-11-22 06:48:43 -06:00
wip
This commit is contained in:
parent
99b2848775
commit
1e1ab9d40e
|
@ -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<S, R> 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<S, R> Client<S, R> where S: Encode + Decode, R: Encode + Decode {
|
||||
pub fn connect(addr: SocketAddr, config: ClientConfig) -> anyhow::Result<Self> {
|
||||
pub fn new(addr: SocketAddr, config: ClientConfig) -> anyhow::Result<Self> {
|
||||
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<S>) -> anyhow::Result<()> {
|
||||
let bytes = bincode::encode_to_vec(packet, BINCODE_CONFIG)?;
|
||||
|
@ -44,7 +59,7 @@ impl<S, R> Client<S, R> 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(())
|
||||
}
|
||||
|
|
|
@ -3,8 +3,16 @@ use bincode::{Encode, Decode};
|
|||
#[repr(u8)]
|
||||
#[derive(Encode, Decode)]
|
||||
pub enum ClientPacket<T> where T: Encode + Decode {
|
||||
Data(T),
|
||||
Connect,
|
||||
Disconnect,
|
||||
Heartbeat,
|
||||
Data(T)
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Encode, Decode)]
|
||||
pub enum ServerPacket<T> where T: Encode + Decode {
|
||||
Data(T),
|
||||
Connected,
|
||||
Disconnected,
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue