start reading future conf conexion

This commit is contained in:
2022-10-08 12:57:59 +02:00
parent 038faae0e4
commit bb6c062be4
6 changed files with 147 additions and 66 deletions

View File

@@ -1,64 +1,18 @@
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, RwLock};
use std::io::prelude::*;
use crate::client::guard;
use std::thread;
use std::time::Duration;
use conf::server_conf;
use std::sync::{Arc, RwLock};
mod client;
mod conf;
mod protocol;
mod server_proxy;
fn main() {
let listener = TcpListener::bind("0.0.0.0:25565").unwrap();
let servers = Arc::new(RwLock::new(conf::Servers::new()));
let guard = Arc::new(RwLock::new(guard::Guard::new()));
for stream in listener.incoming() {
if guard.read().unwrap().can_add(){
match stream {
Ok(stream) => {
let g = guard.clone();
let s = servers.clone();
thread::spawn(|| read_connection(stream, s , g));
},
Err(_e) => println!("{}",_e),
}
}
}
let servers = Arc::new(RwLock::new(conf::Config::new()));
let s1 = servers.clone();
let s2 = servers.clone();
let stop1 = thread::spawn(|| server_proxy::start_proxy(s1));
let stop2 = thread::spawn(|| conf::server_conf::server_conf(s2));
stop1.join();
stop2.join();
}
fn read_connection(mut stream: TcpStream,
servers: Arc<RwLock<conf::Servers>>,
guard: Arc<RwLock<guard::Guard>> ) {
let mut buf: [u8; 256] = [1; 256];
stream.set_read_timeout(Some(Duration::from_millis(5000)));
let leng = match stream.read(&mut buf) {
Ok(l) => l,
Err(_e) => return,
};
let hs = protocol::HandShake::new(&mut buf[.. leng]);
if hs.is_handshake() { //Filtra los ping, solo controlamos los handshakes
conect_server(servers, hs, stream, guard);
}
}
fn conect_server(servers: Arc<RwLock<conf::Servers>>,
mut hs: protocol::HandShake,
stream: TcpStream,
guard: Arc<RwLock<guard::Guard>>){
match servers.read().unwrap().get_server(&hs.get_host_name()) {
Some(s) => {
hs.replace_port(s.1);
let mut sstream = TcpStream::connect(s.0 + ":" + &s.1.to_string()).unwrap();
sstream.write(hs.get_raw());
let c1 = client::Client::new(stream,sstream, hs);
guard.write().unwrap().add_thread(c1.start_proxy());
},
None => println!("No server found for {}", hs.get_host_name())
}
}