blob: c69f3da6a884ed9b2df7b418b39a9fa5697b9009 (
plain) (
tree)
|
|
// 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()
}
}
|