diff options
Diffstat (limited to 'client/src/server_connection')
-rw-r--r-- | client/src/server_connection/mod.rs | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/client/src/server_connection/mod.rs b/client/src/server_connection/mod.rs new file mode 100644 index 0000000..c69f3da --- /dev/null +++ b/client/src/server_connection/mod.rs @@ -0,0 +1,50 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use bowshock::net::{Request, Response}; +use bzipper::Buffer; +use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; + +pub struct ServerConnection { + socket: UdpSocket, + + request_buf: Buffer<Request>, + response_buf: Buffer<Response>, + + #[expect(unused)] + addr: SocketAddr, +} + +impl ServerConnection { + #[must_use] + pub fn new<A: ToSocketAddrs>(addr: A) -> Self { + let addr = addr + .to_socket_addrs() + .unwrap() + .next() + .unwrap(); + + let socket = UdpSocket::bind("0.0.0.0:0").unwrap(); + socket.connect(addr).unwrap(); + + Self { + socket, + + request_buf: Buffer::new(), + response_buf: Buffer::new(), + + addr, + } + } + + pub fn send_request(&mut self, request: &Request) { + self.request_buf.write(request).unwrap(); + self.socket.send(&self.request_buf).unwrap(); + } + + pub fn recieve_response(&mut self) -> Response { + let len = self.socket.recv(&mut self.response_buf).unwrap(); + assert_eq!(len, self.response_buf.len()); + + self.response_buf.read().unwrap() + } +} |