This commit is contained in:
griffi-gh 2023-02-01 03:24:06 +01:00
parent 728c468a70
commit e6ec24a55c

View file

@ -5,31 +5,35 @@ use std::{
use bincode::{Encode, Decode}; use bincode::{Encode, Decode};
use crate::{BINCODE_CONFIG, packet::ClientPacket}; use crate::{BINCODE_CONFIG, packet::ClientPacket};
pub struct Client<T> where T: Encode + Decode { pub struct Client<S, R> where S: Encode + Decode, R: Encode + Decode {
socket: UdpSocket, socket: UdpSocket,
_marker: PhantomData<T> _s: PhantomData<S>,
_r: PhantomData<R>,
} }
impl<T> Client<T> where T: Encode + Decode { impl<S, R> Client<S, R> where S: Encode + Decode, R: Encode + Decode {
pub fn connect(addr: SocketAddr) -> anyhow::Result<Self> { pub fn connect(addr: SocketAddr) -> anyhow::Result<Self> {
let bind_addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); let bind_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let socket = UdpSocket::bind(bind_addr)?; let socket = UdpSocket::bind(bind_addr)?;
socket.set_nonblocking(true)?; socket.set_nonblocking(true)?;
socket.connect(addr)?; socket.connect(addr)?;
Ok(Self { let client = Self {
socket, socket,
_marker: PhantomData _s: PhantomData,
}) _r: PhantomData,
};
client.send_packet(&ClientPacket::Connect)?;
Ok(client)
} }
fn send_packet(&self, packet: &ClientPacket<T>) -> anyhow::Result<()> { fn send_packet(&self, packet: &ClientPacket<S>) -> anyhow::Result<()> {
let bytes = bincode::encode_to_vec(packet, BINCODE_CONFIG)?; let bytes = bincode::encode_to_vec(packet, BINCODE_CONFIG)?;
self.socket.send(&bytes)?; self.socket.send(&bytes)?;
Ok(()) Ok(())
} }
pub fn send(&self, message: T) -> anyhow::Result<()> { pub fn send_message(&self, message: S) -> anyhow::Result<()> {
self.send_packet(&ClientPacket::Data(message))?; self.send_packet(&ClientPacket::Data(message))?;
Ok(()) Ok(())
} }
pub fn disconnect(&self) -> anyhow::Result<()> { pub fn disconnect(self) -> anyhow::Result<()> {
self.send_packet(&ClientPacket::Disconnect)?; self.send_packet(&ClientPacket::Disconnect)?;
Ok(()) Ok(())
} }