Allow multiple connections

This commit is contained in:
Silvio Braendle 2025-01-06 15:19:57 +01:00
parent 1986341fdc
commit 2b8a8a7c84
No known key found for this signature in database
GPG key ID: 553A5A37BA69D8AE
2 changed files with 27 additions and 20 deletions

View file

@ -2,6 +2,7 @@ use crate::protocol::Message;
use crate::sound_scheduler::SoundScheduler; use crate::sound_scheduler::SoundScheduler;
use std::io::Read; use std::io::Read;
use std::net::{TcpListener, TcpStream}; use std::net::{TcpListener, TcpStream};
use std::thread;
pub struct ClientHandler; pub struct ClientHandler;
@ -24,14 +25,14 @@ impl ClientHandler {
let listener = TcpListener::bind("127.0.0.1:3000").expect("Could not bind to address"); let listener = TcpListener::bind("127.0.0.1:3000").expect("Could not bind to address");
for stream in listener.incoming() { for stream in listener.incoming() {
match stream { thread::spawn(move || match stream {
Ok(stream) => { Ok(stream) => {
ClientHandler::handle_client(stream); ClientHandler::handle_client(stream);
} }
Err(e) => { Err(e) => {
eprintln!("Error: {}", e); eprintln!("Error: {}", e);
} }
} });
} }
} }
} }

View file

@ -1,28 +1,34 @@
use crate::protocol::PlaySound; use crate::protocol::PlaySound;
use crate::sound_player::SoundPlayer; use crate::sound_player::SoundPlayer;
use std::thread::sleep; use std::thread::{self, sleep};
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub struct SoundScheduler; pub struct SoundScheduler;
impl SoundScheduler { impl SoundScheduler {
pub fn handle_scheduled_sound(play_msg: PlaySound) { pub fn handle_scheduled_sound(play_msg: PlaySound) {
let PlaySound { thread::spawn(move || {
sound_data, let PlaySound {
timestamp, sound_data,
} = play_msg; timestamp,
println!("Scheduled sound: len={:?} at {:?}", sound_data.len(), timestamp); } = play_msg;
let now_micros = SystemTime::now() println!(
.duration_since(UNIX_EPOCH) "Scheduled sound: len={:?} at {:?}",
.expect("Could not get time") sound_data.len(),
.as_micros(); timestamp
let wait = timestamp as i128 - now_micros as i128; );
if wait <= 0 { let now_micros = SystemTime::now()
println!("Too late to play sound"); .duration_since(UNIX_EPOCH)
return; .expect("Could not get time")
} .as_micros();
sleep(Duration::from_micros(wait as u64)); let wait = timestamp as i128 - now_micros as i128;
println!("Playing sound..."); if wait <= 0 {
SoundPlayer::play_sound(sound_data); println!("Too late to play sound");
return;
}
sleep(Duration::from_micros(wait as u64));
println!("Playing sound...");
SoundPlayer::play_sound(sound_data);
});
} }
} }