summaryrefslogtreecommitdiff
path: root/client/src/server_connection/mod.rs
blob: c69f3da6a884ed9b2df7b418b39a9fa5697b9009 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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()
	}
}