// 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, response_buf: Buffer, #[expect(unused)] addr: SocketAddr, } impl ServerConnection { #[must_use] pub fn new(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() } }