start reading future conf conexion
This commit is contained in:
61
src/server_proxy.rs
Normal file
61
src/server_proxy.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::io::prelude::*;
|
||||
use crate::client::guard;
|
||||
use crate::client;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use crate::protocol;
|
||||
use crate::conf;
|
||||
|
||||
pub fn start_proxy(servers: Arc<RwLock<conf::Config>>){
|
||||
let listener = TcpListener::bind(String::from("0.0.0.0:") + servers.read().unwrap().get_port()).unwrap();
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_connection(mut stream: TcpStream,
|
||||
servers: Arc<RwLock<conf::Config>>,
|
||||
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::Config>>,
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user