NetworkKVM/server/src/main.rs
2023-04-16 17:33:28 -04:00

73 lines
1.6 KiB
Rust

use std::collections::VecDeque;
use std::io;
use std::net::SocketAddr;
use messages::client_registration::ClientRegistration;
use messages::serialization::{DeserializeMessage, read_message_data, SerializeMessage};
use crate::input::read_inputs;
use crate::net::tcp_server::{NextIntent, TcpClient, TcpServer};
mod net;
mod input;
mod client;
fn main() -> io::Result<()> {
// let addr = SocketAddr::from(([127, 0, 0, 1], 4433));
// let mut server: TcpServer<KvmClient> = TcpServer::new(addr)?;
//
// server.listen()?;
read_inputs()?;
Ok(())
}
static mut AUTO_ID: u8 = 0;
struct KvmClient {
id: u8,
write_buffer: VecDeque<Vec<u8>>,
}
impl TcpClient for KvmClient {
fn new() -> Self {
let id = unsafe {
AUTO_ID += 1;
AUTO_ID
};
println!("New client ({id})");
KvmClient {
id,
write_buffer: VecDeque::new(),
}
}
fn read(&self, buf: &[u8]) -> NextIntent {
let (message_type, data) = read_message_data(buf).expect("Received invalid message");
println!("Received {:?} message with {} bytes", message_type, data.len());
NextIntent::Read
}
fn get_next_write(&mut self) -> (Vec<u8>, NextIntent) {
let data = self.write_buffer.pop_front().unwrap();
(data, NextIntent::Read)
}
fn close(&self) {
println!("Client {} disconnected", self.id);
}
}
impl KvmClient {
pub fn write<T>(&mut self, data: &T)
where T: SerializeMessage {
let buf = data.serialize();
self.write_buffer.push_back(buf);
}
}