2023-02-05 19:15:19 -06:00
|
|
|
use std::{net::{UdpSocket, SocketAddr}, time::Instant};
|
2023-02-06 12:19:02 -06:00
|
|
|
use anyhow::{Result, bail};
|
2023-02-05 19:15:19 -06:00
|
|
|
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-06 12:30:26 -06:00
|
|
|
fn add_client(&mut self, addr: SocketAddr) -> Result<ClientId> {
|
2023-02-06 12:19:02 -06:00
|
|
|
let Some(id) = (1..=self.config.max_clients)
|
2023-02-05 20:48:43 -06:00
|
|
|
.map(|x| ClientId::new(x as _).unwrap())
|
2023-02-06 12:19:02 -06:00
|
|
|
.find(|i| self.clients.contains_key(i)) else {
|
|
|
|
bail!("Server full");
|
|
|
|
};
|
|
|
|
if self.clients.iter().any(|x| x.1.addr == addr) {
|
|
|
|
bail!("Already connected from the same address");
|
|
|
|
}
|
2023-02-05 20:48:43 -06:00
|
|
|
self.clients.insert(id, ConnectedClient {
|
|
|
|
id,
|
2023-02-06 12:19:02 -06:00
|
|
|
addr,
|
2023-02-05 20:48:43 -06:00
|
|
|
timeout: Instant::now(),
|
|
|
|
});
|
2023-02-06 12:19:02 -06:00
|
|
|
log::info!("Client with id {id} connected");
|
|
|
|
Ok(id)
|
2023-02-05 20:48:43 -06:00
|
|
|
}
|
2023-02-05 19:40:45 -06:00
|
|
|
pub fn update(&mut self) {
|
|
|
|
let mut buf = Vec::new();
|
2023-02-06 13:54:30 -06:00
|
|
|
loop {
|
|
|
|
if self.socket.recv(&mut buf).is_ok() {
|
|
|
|
todo!()
|
|
|
|
} else {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
buf.clear()
|
2023-02-05 19:40:45 -06:00
|
|
|
}
|
2023-02-06 13:54:30 -06:00
|
|
|
|
2023-02-05 19:40:45 -06:00
|
|
|
}
|
2023-01-31 20:16:23 -06:00
|
|
|
}
|