Server and client communicates through unix socket

This commit is contained in:
2019-12-17 01:09:17 +01:00
parent fcc5d5727a
commit ae632df144
5 changed files with 326 additions and 241 deletions

19
src/bin/client.rs Normal file
View File

@ -0,0 +1,19 @@
use std::io;
use std::os::unix::net::UnixStream;
fn main() {
let mut stream = match UnixStream::connect("/tmp/clichess.socket") {
Ok(sock) => sock,
Err(_) => {
println!("clichess daemon is not running.");
return;
}
};
let mut buffer = String::new();
let input = clichess::read_from_stream(&stream);
println!("{}", input);
io::stdin().read_line(&mut buffer).unwrap();
clichess::write_to_stream(&mut stream, String::from(buffer.trim()));
let response = clichess::read_from_stream(&stream);
println!("{}", response);
}

64
src/bin/server.rs Normal file
View File

@ -0,0 +1,64 @@
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),
);
}
}