2023-02-05 19:15:19 -06:00
|
|
|
use std::{net::{UdpSocket, SocketAddr}, time::Instant};
|
|
|
|
use hashbrown::HashMap;
|
|
|
|
use nohash_hasher::BuildNoHashHasher;
|
|
|
|
use crate::{BINCODE_CONFIG, common::{ClientId, MAX_CLIENTS}};
|
|
|
|
|
|
|
|
pub struct ConnectedClient {
|
|
|
|
id: ClientId,
|
|
|
|
addr: SocketAddr,
|
|
|
|
timeout: Instant,
|
|
|
|
}
|
2023-01-31 20:16:23 -06:00
|
|
|
|
2023-02-05 20:48:43 -06:00
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
|
|
pub struct ServerConfig {
|
|
|
|
pub max_clients: usize,
|
|
|
|
}
|
|
|
|
impl Default for ServerConfig {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
|
|
|
max_clients: MAX_CLIENTS,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-31 20:16:23 -06:00
|
|
|
pub struct Server {
|
|
|
|
socket: UdpSocket,
|
2023-02-05 20:48:43 -06:00
|
|
|
clients: HashMap<ClientId, ConnectedClient, BuildNoHashHasher<u8>>,
|
|
|
|
config: ServerConfig,
|
2023-01-31 20:16:23 -06:00
|
|
|
}
|
|
|
|
impl Server {
|
2023-02-05 20:48:43 -06:00
|
|
|
pub fn bind(addr: SocketAddr, config: ServerConfig) -> anyhow::Result<Self> {
|
|
|
|
assert!(config.max_clients <= MAX_CLIENTS);
|
2023-01-31 20:16:23 -06:00
|
|
|
let socket = UdpSocket::bind(addr)?;
|
|
|
|
socket.set_nonblocking(true)?;
|
2023-02-05 19:41:34 -06:00
|
|
|
//socket.set_broadcast(true)?;
|
2023-02-05 19:15:19 -06:00
|
|
|
Ok(Self {
|
2023-02-05 20:48:43 -06:00
|
|
|
config,
|
2023-02-05 19:15:19 -06:00
|
|
|
socket,
|
|
|
|
clients: HashMap::with_capacity_and_hasher(MAX_CLIENTS, BuildNoHashHasher::default())
|
|
|
|
})
|
2023-01-31 20:16:23 -06:00
|
|
|
}
|
2023-02-05 20:48:43 -06:00
|
|
|
/// Returns None if there are no free spots left
|
|
|
|
fn connect_client(&mut self) -> Option<ClientId> {
|
|
|
|
let id = (1..=self.config.max_clients)
|
|
|
|
.map(|x| ClientId::new(x as _).unwrap())
|
|
|
|
.find(|i| self.clients.contains_key(i))?;
|
|
|
|
self.clients.insert(id, ConnectedClient {
|
|
|
|
id,
|
|
|
|
addr: "0.0.0.0:0".parse().unwrap(),
|
|
|
|
timeout: Instant::now(),
|
|
|
|
});
|
|
|
|
todo!();
|
|
|
|
Some(id)
|
|
|
|
}
|
2023-02-05 19:40:45 -06:00
|
|
|
pub fn update(&mut self) {
|
|
|
|
let mut buf = Vec::new();
|
|
|
|
if self.socket.recv(&mut buf).is_ok() {
|
|
|
|
todo!()
|
|
|
|
}
|
|
|
|
}
|
2023-01-31 20:16:23 -06:00
|
|
|
}
|