Skip to content

Instantly share code, notes, and snippets.

@nixpulvis
Last active November 29, 2018 13:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nixpulvis/1fac17b84aab035798ae to your computer and use it in GitHub Desktop.
Save nixpulvis/1fac17b84aab035798ae to your computer and use it in GitHub Desktop.
// extern crate take5;
// extern crate remote;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream, TcpListener, Shutdown};
use std::thread;
use std::time::Duration;
use std::sync::{Arc, Mutex};
// use take5::player::AiPlayer;
// use remote::Client;
fn process(mut reader: TcpStream, streams: Arc<Mutex<Vec<TcpStream>>>) {
loop {
let mut buf = [0; 256];
if let Ok(read) = reader.read(&mut buf) {
println!("READ: {}", read);
if read > 0 {
for mut writer in &*streams.lock().unwrap() {
if writer.peer_addr().unwrap() != reader.peer_addr().unwrap() {
println!("writing to {:?}", writer.peer_addr().unwrap());
writer.write(&mut buf).unwrap();
}
}
}
} else {
println!("ERR");
}
}
}
fn main() {
let address = "127.0.0.1:45678";
let clients = Arc::new(Mutex::new(Vec::new()));
let proxy_handle = thread::spawn(move || {
let proxy = TcpListener::bind(address).unwrap();
for stream in proxy.incoming() {
match stream {
Ok(stream) => {
let reader = stream.try_clone().unwrap();
let clients = clients.clone();
clients.lock().unwrap().push(stream);
thread::spawn(move || process(reader, clients));
}
Err(e) => {
panic!("{}", e);
}
}
}
});
thread::sleep(Duration::from_millis(250));
// let client_handle = thread::spawn(move || {
// //let player = Box::new(StdinPlayer::new(1));
// let player = Box::new(AiPlayer::new(1));
// let mut client = Client::new("127.0.0.1:45678", player, true).unwrap_or_else(|e| {
// panic!("{}", e);
// });
// match client.start() {
// Ok(_) => println!("Game Over"),
// Err(_) => panic!("Something bad happened while playing."),
// }
// });
let a = thread::spawn(move || {
let mut stream = TcpStream::connect("127.0.0.1:45678").unwrap();
// ignore the Result
let _ = stream.write(&[1]);
let _ = stream.read(&mut [0; 128]); // ignore here too
stream.shutdown(Shutdown::Both);
});
let b = thread::spawn(move || {
let mut stream = TcpStream::connect("127.0.0.1:45678").unwrap();
// ignore the Result
let _ = stream.write(&[1]);
let _ = stream.read(&mut [0; 128]); // ignore here too
stream.shutdown(Shutdown::Both);
});
a.join().unwrap();
b.join().unwrap();
// client_handle.join().unwrap();
proxy_handle.join().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment