kubi/kubi-udp/src/client.rs

42 lines
1.2 KiB
Rust
Raw Normal View History

2023-01-31 20:16:23 -06:00
use std::{
net::{UdpSocket, SocketAddr},
marker::PhantomData
};
use bincode::{Encode, Decode};
use crate::{BINCODE_CONFIG, packet::ClientPacket};
2023-01-31 20:24:06 -06:00
pub struct Client<S, R> where S: Encode + Decode, R: Encode + Decode {
2023-01-31 20:16:23 -06:00
socket: UdpSocket,
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-01-31 20:16:23 -06:00
pub fn connect(addr: SocketAddr) -> 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)?;
2023-01-31 20:24:06 -06:00
let client = Self {
2023-01-31 20:16:23 -06:00
socket,
2023-01-31 20:24:06 -06:00
_s: PhantomData,
_r: PhantomData,
};
client.send_packet(&ClientPacket::Connect)?;
Ok(client)
2023-01-31 20:16:23 -06:00
}
2023-01-31 20:25:39 -06:00
//maybe move generics here if possible?
2023-01-31 20:24:06 -06:00
fn send_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-01-31 20:16:23 -06:00
self.send_packet(&ClientPacket::Data(message))?;
Ok(())
}
2023-01-31 20:24:06 -06:00
pub fn disconnect(self) -> anyhow::Result<()> {
2023-01-31 20:16:23 -06:00
self.send_packet(&ClientPacket::Disconnect)?;
Ok(())
}
}