diff --git a/src/client_handler.rs b/src/client_handler.rs index e295afb..d4d2f11 100644 --- a/src/client_handler.rs +++ b/src/client_handler.rs @@ -2,6 +2,7 @@ use crate::protocol::Message; use crate::sound_scheduler::SoundScheduler; use std::io::Read; use std::net::{TcpListener, TcpStream}; +use std::thread; pub struct ClientHandler; @@ -24,14 +25,14 @@ impl ClientHandler { let listener = TcpListener::bind("127.0.0.1:3000").expect("Could not bind to address"); for stream in listener.incoming() { - match stream { + thread::spawn(move || match stream { Ok(stream) => { ClientHandler::handle_client(stream); } Err(e) => { eprintln!("Error: {}", e); } - } + }); } } } diff --git a/src/sound_scheduler.rs b/src/sound_scheduler.rs index 4ffec7d..d434359 100644 --- a/src/sound_scheduler.rs +++ b/src/sound_scheduler.rs @@ -1,28 +1,34 @@ use crate::protocol::PlaySound; use crate::sound_player::SoundPlayer; -use std::thread::sleep; +use std::thread::{self, sleep}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub struct SoundScheduler; impl SoundScheduler { pub fn handle_scheduled_sound(play_msg: PlaySound) { - let PlaySound { - sound_data, - timestamp, - } = play_msg; - println!("Scheduled sound: len={:?} at {:?}", sound_data.len(), timestamp); - let now_micros = SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("Could not get time") - .as_micros(); - let wait = timestamp as i128 - now_micros as i128; - if wait <= 0 { - println!("Too late to play sound"); - return; - } - sleep(Duration::from_micros(wait as u64)); - println!("Playing sound..."); - SoundPlayer::play_sound(sound_data); + thread::spawn(move || { + let PlaySound { + sound_data, + timestamp, + } = play_msg; + println!( + "Scheduled sound: len={:?} at {:?}", + sound_data.len(), + timestamp + ); + let now_micros = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("Could not get time") + .as_micros(); + let wait = timestamp as i128 - now_micros as i128; + if wait <= 0 { + println!("Too late to play sound"); + return; + } + sleep(Duration::from_micros(wait as u64)); + println!("Playing sound..."); + SoundPlayer::play_sound(sound_data); + }); } }