65 lines
1.8 KiB
Rust
65 lines
1.8 KiB
Rust
use clichess;
|
|
use shakmaty::{Chess, Color};
|
|
use std::fs;
|
|
use std::io::prelude::*;
|
|
use std::os::unix::net::{UnixListener, UnixStream};
|
|
use std::str;
|
|
use std::sync::{Arc, Mutex};
|
|
use std::thread;
|
|
|
|
struct Server {
|
|
id: usize,
|
|
chess_position: Arc<Mutex<Chess>>,
|
|
}
|
|
|
|
fn main() {
|
|
let chess = Arc::new(Mutex::new(Chess::default()));
|
|
let mut counter = 0;
|
|
fs::remove_file("/tmp/clichess.socket");
|
|
|
|
let listener = UnixListener::bind("/tmp/clichess.socket").unwrap();
|
|
|
|
// accept connections and process them, spawning a new thread for each one
|
|
for stream in listener.incoming() {
|
|
match stream {
|
|
Ok(stream) => {
|
|
let chess = Arc::clone(&chess);
|
|
/* connection succeeded */
|
|
let server = Server {
|
|
id: counter,
|
|
chess_position: chess,
|
|
};
|
|
thread::spawn(|| handle_client(stream, server));
|
|
counter += 1;
|
|
}
|
|
Err(err) => {
|
|
println!("Could not create a connection: {}", err);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn handle_client(mut stream: UnixStream, server: Server) {
|
|
{
|
|
let chess = server.chess_position.lock().unwrap();
|
|
clichess::write_to_stream(
|
|
&mut stream,
|
|
clichess::board_representation(&chess, Color::White),
|
|
);
|
|
}
|
|
//let go of the lock while waiting for user input.
|
|
let input = clichess::read_from_stream(&stream);
|
|
{
|
|
let mut chess = server.chess_position.lock().unwrap();
|
|
match clichess::try_to_play_move(&chess, input) {
|
|
Ok(played_chess) => *chess = played_chess,
|
|
Err(e) => println!("Error: {}", e),
|
|
};
|
|
clichess::write_to_stream(
|
|
&mut stream,
|
|
clichess::board_representation(&chess, Color::White),
|
|
);
|
|
}
|
|
}
|