57 lines
2.0 KiB
Rust
57 lines
2.0 KiB
Rust
use std::{
|
|
io::{ prelude::*, BufReader, BufWriter, WriterPanicked },
|
|
net::{ TcpListener, TcpStream },
|
|
};
|
|
|
|
const PROTOCOL_ERROR_STRING: &str = "Client/Server protocol mismatch";
|
|
|
|
pub fn main() {
|
|
let listener = TcpListener::bind("0.0.0.0:8000").unwrap();
|
|
|
|
for stream in listener.incoming() {
|
|
let (reader, writer) = create_buffers(stream.unwrap().try_clone().unwrap());
|
|
let result = check_protocol(reader, writer).unwrap();
|
|
if result == "Uno-Enthusiast99" {
|
|
println!("It works!");
|
|
}
|
|
}
|
|
}
|
|
|
|
fn create_buffers(stream: TcpStream) -> (BufReader<TcpStream>, BufWriter<TcpStream>) {
|
|
(
|
|
BufReader::new(stream.try_clone().expect("Could not clone TcpStreams")),
|
|
BufWriter::new(stream),
|
|
)
|
|
}
|
|
fn check_protocol(
|
|
reader: BufReader<TcpStream>,
|
|
mut writer: BufWriter<TcpStream>
|
|
) -> Result<String, String> {
|
|
let protocol_error_string = PROTOCOL_ERROR_STRING.to_string();
|
|
let init_message: Vec<_> = reader
|
|
.lines()
|
|
.map(|result| result.unwrap())
|
|
.take_while(|line| !line.is_empty())
|
|
.collect();
|
|
let mut init_message = init_message.iter();
|
|
let is_valid1 = init_message.next().unwrap_or_else(|| &protocol_error_string) == "app:uno";
|
|
let is_valid2= init_message.next().unwrap_or_else(|| &protocol_error_string) == "version:0.1";
|
|
let player_name: &str = init_message.next().unwrap_or_else(|| &protocol_error_string);
|
|
let is_valid3 = if player_name != "invalid" && player_name.contains("player_name:") {
|
|
true
|
|
} else {
|
|
false
|
|
};
|
|
if init_message.next() != None || !(is_valid1 && is_valid2 && is_valid3){
|
|
writer.write(protocol_error_string.as_bytes()).unwrap();
|
|
writer.flush().unwrap();
|
|
return Err(protocol_error_string);
|
|
}
|
|
writer.write("Ok".as_bytes()).unwrap();
|
|
writer.flush().unwrap();
|
|
return Ok(player_name.split(':').collect::<Vec<_>>()[1].to_owned());
|
|
}
|
|
|
|
// fn register_player(player_name : &str, reader : BufReader, writer : BufWriter){
|
|
//
|
|
// }
|