Convert to UDP

This commit is contained in:
Silvio Braendle 2025-01-20 16:14:07 +01:00
parent d0e86603ae
commit a6a08ad768
No known key found for this signature in database
GPG key ID: 553A5A37BA69D8AE
2 changed files with 22 additions and 33 deletions

View file

@ -1,42 +1,30 @@
use crate::protocol::Message;
use crate::sound_scheduler::SoundScheduler;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::net::UdpSocket;
pub struct ClientHandler;
impl ClientHandler {
fn handle_client(mut stream: TcpStream) {
println!("Handling client: {:?}", stream);
loop {
match bincode::deserialize_from::<&mut TcpStream, Message>(&mut stream) {
Ok(message) => {
match message {
Message::PlaySound(play_sound) => {
SoundScheduler::handle_scheduled_sound(play_sound);
}
}
}
Err(e) => {
eprintln!("Error deserializing message: {}", e);
break;
}
fn handle_message(msg: Message) {
match msg {
Message::PlaySound(play_sound) => {
SoundScheduler::handle_scheduled_sound(play_sound);
}
}
}
pub fn listen() {
let listener = TcpListener::bind("0.0.0.0:3000").expect("Could not bind to address");
let socket = UdpSocket::bind("0.0.0.0:3000").expect("Could not bind to address");
for stream in listener.incoming() {
thread::spawn(move || match stream {
Ok(stream) => {
ClientHandler::handle_client(stream);
}
Err(e) => {
eprintln!("Error: {}", e);
}
});
println!("Listening on {}", socket.local_addr().unwrap());
loop {
let mut data = [0; 1_048_576];
let (amt, src) = socket.recv_from(&mut data).expect("Didn't receive data");
println!("Received {} bytes from {}", amt, src);
let data = &mut data[..amt];
let msg = bincode::deserialize::<Message>(data).expect("Failed to deserialize");
ClientHandler::handle_message(msg);
}
}
}

View file

@ -1,8 +1,8 @@
use std::io::BufReader;
use std::net::TcpStream;
use std::fs::File;
use std::io::{BufReader, Read};
use std::net::UdpSocket;
use std::thread;
use std::time::{Duration, SystemTime};
use std::{fs::File, io::Write};
use rodio::{Decoder, Source};
@ -26,7 +26,7 @@ impl Dispatcher {
let channels = source.channels();
let sample_rate = source.sample_rate();
let duration = source.total_duration().unwrap();
let chunk_len = Duration::from_secs(1);
let chunk_len = Duration::from_millis(200);
let mut offset = Duration::from_secs(0);
@ -38,7 +38,8 @@ impl Dispatcher {
let source = source.clone();
thread::spawn(move || {
let mut sock = TcpStream::connect(addr).expect("Failed to connect");
let sock = UdpSocket::bind("0.0.0.0:0").expect("Failed to bind");
sock.connect(addr.clone()).expect("Failed to connect");
while offset < duration {
let sound_data = source
@ -57,7 +58,7 @@ impl Dispatcher {
});
let buf = bincode::serialize(&msg).expect("Failed to serialize");
sock.write_all(&buf).unwrap();
sock.send(&buf).expect("Failed to send");
}
});
}