Skip to content

Commit

Permalink
[119] (fix on multiplayer-fix) Make multiplayer connection non-blocki…
Browse files Browse the repository at this point in the history
…ng and improve logging

- `src/app.rs`:
    - Add debug logging around game server setup to track connection flow

- `src/game_logic/opponent.rs`:
    - Make wait_for_game_start non-blocking by using non-blocking socket mode
    - Add proper error handling and logging for socket operations
    - Return boolean instead of blocking/panicking

- `src/handler.rs`:
    - Adjust log levels to use trace/debug instead of info for routine events
    - Clean up logging to reduce noise while keeping important info

- `src/main.rs`:
    - Update main loop to handle non-blocking opponent connection
    - Remove noisy loop/tick logging
    - Only update game state when connection is successful

- `src/server/game_server.rs`:
    - Change server logs to debug level
    - Add more detailed logging around client handling
    - Clean up log messages for better readability
  • Loading branch information
TomPlanche committed Feb 1, 2025
1 parent 06c80be commit c5de015
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 13 deletions.
7 changes: 6 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,17 @@ impl App {

pub fn setup_game_server(&mut self, host_color: PieceColor) {
let is_host_white = host_color == PieceColor::White;


log::info!("About to setup game server");

std::thread::spawn(move || {
let game_server = GameServer::new(is_host_white);
log::info!("Game server created");
game_server.run();
});

log::info!("Game server thread spawned");

sleep(Duration::from_millis(100));
}

Expand Down
31 changes: 25 additions & 6 deletions src/game_logic/opponent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,32 @@ pub fn get_color_from_stream(mut stream: &TcpStream) -> PieceColor {
}
}

pub fn wait_for_game_start(mut stream: &TcpStream) {
pub fn wait_for_game_start(mut stream: &TcpStream) -> bool {
let mut buffer = [0; 5];
let bytes_read = stream.read(&mut buffer).unwrap(); // Number of bytes read
let response = String::from_utf8_lossy(&buffer[..bytes_read]).to_string();

match response.as_str() {
"s" => (),
_ => panic!("Failed to get color from stream"),
// Set non-blocking mode
if let Err(e) = stream.set_nonblocking(true) {
log::error!("Failed to set non-blocking mode: {}", e);
return false;
}

// Read result
let result = match stream.read(&mut buffer) {
Ok(bytes_read) => {
let response = String::from_utf8_lossy(&buffer[..bytes_read]).to_string();
response == "s"
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => false,
Err(e) => {
log::error!("Error reading from stream: {}", e);
false
}
};

// Reset to blocking mode
if let Err(e) = stream.set_nonblocking(false) {
log::error!("Failed to reset blocking mode: {}", e);
}

result
}
6 changes: 6 additions & 0 deletions src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ use ratatui::crossterm::event::{

/// Handles the key events and updates the state of [`App`].
pub fn handle_key_events(key_event: KeyEvent, app: &mut App) -> AppResult<()> {
log::trace!("Entering handle_key_events");
if key_event.kind != KeyEventKind::Press {
log::debug!("Ignoring non-press event");
// crossterm on Windows sends Release and Repeat events as well, which we ignore.
return Ok(());
}
Expand All @@ -26,6 +28,10 @@ pub fn handle_key_events(key_event: KeyEvent, app: &mut App) -> AppResult<()> {
}
}

log::debug!("Key event: {:?}", key_event);
log::debug!("Current page: {:?}", app.current_page);
log::debug!("Current popup: {:?}", app.current_popup);

if app.current_popup == Some(Popups::EnterHostIP) {
if key_event.kind == KeyEventKind::Press {
match key_event.code {
Expand Down
7 changes: 4 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,10 @@ fn main() -> AppResult<()> {
.is_some_and(|opponent| !opponent.game_started)
{
let opponent = app.game.opponent.as_mut().unwrap();
wait_for_game_start(opponent.stream.as_ref().unwrap());
opponent.game_started = true;
app.current_popup = None;
if wait_for_game_start(opponent.stream.as_ref().unwrap()) {
opponent.game_started = true;
app.current_popup = None;
}
}

// If it's the opponent turn, wait for the opponent to move
Expand Down
12 changes: 9 additions & 3 deletions src/server/game_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@ impl GameServer {
}

pub fn run(&self) {
log::debug!("Starting game server");

let listener = TcpListener::bind("0.0.0.0:2308").expect("Failed to create listener");
listener
.set_nonblocking(true)
.expect("Failed to set listener to non-blocking");

log::debug!("Server listening on port 2308");

let state = self.clients.clone();
let stop_signal = self.stop_signal.clone();
Expand Down Expand Up @@ -104,10 +105,15 @@ fn handle_client(
stop_signal: Arc<AtomicBool>,
mut stream: TcpStream,
) {
log::debug!("New client handler started");

loop {
let mut buffer = [0; 5];
let addr = stream.peer_addr().unwrap().to_string();

log::debug!("Waiting for client data");
let bytes_read = stream.read(&mut buffer).unwrap_or(0);
log::debug!("Received {} bytes from client", bytes_read);

if bytes_read == 0 {
broadcast_message(state.clone(), "ended".to_string(), &addr);
Expand Down

0 comments on commit c5de015

Please sign in to comment.