rust_voice_chat/src/client.rs
2025-03-03 15:25:24 +03:00

57 lines
1.7 KiB
Rust

use std::{net::SocketAddr, path::Path};
use s2n_quic::{Client, client::Connect};
use tokio::{
io::AsyncWriteExt,
sync::{broadcast, oneshot},
};
use crate::{
BUFFER_LENGTH, ClientConfig,
voice::{play, record},
};
pub async fn run<'a>(client_config: ClientConfig<'a>) {
let client = Client::builder()
.with_io("0:0")
.unwrap()
.with_tls(Path::new("certificates/cert.pem"))
.unwrap()
.start()
.unwrap();
println!("Client Address = {}", client.local_addr().unwrap());
let connect = Connect::new(client_config.server_address.parse::<SocketAddr>().unwrap())
.with_server_name("localhost");
let mut connection = match client.connect(connect).await {
Ok(connection) => connection,
Err(err_val) => {
eprintln!("Error: Client Connection | {}", err_val);
return;
}
};
connection.keep_alive(true).unwrap();
let (microphone_sender, mut microphone_receiver) = broadcast::channel::<f32>(BUFFER_LENGTH);
let (stop_signal_sender, stop_signal_receiver) = oneshot::channel::<bool>();
let stream = connection.open_bidirectional_stream().await.unwrap();
tokio::spawn(record(microphone_sender, stop_signal_receiver));
let (receive_stream, mut send_stream) = stream.split();
while let Ok(sample) = microphone_receiver.recv().await {
send_stream
.send(sample.to_le_bytes().to_vec().into())
.await
.unwrap();
}
if let Err(err_val) = send_stream.close().await {
eprintln!("Error: Stream Close | {}", err_val);
}
if let Err(err_val) = send_stream.shutdown().await {
eprintln!("Error: Stream Shutdown| {}", err_val);
}
}