made ApplicationMessage cloneable

This commit is contained in:
Nickiel12 2024-08-20 17:16:48 -07:00
parent 1e37189866
commit e9b4bfee32

View file

@ -3,7 +3,7 @@ use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use async_channel::{Receiver, Sender};
use futures_util::stream::{SplitStream, StreamExt};
use futures_util::stream::{SplitSink, SplitStream, StreamExt};
use futures_util::SinkExt;
use serde::{Serialize, Deserialize};
use tokio::{
@ -18,7 +18,7 @@ use webrtc::peer_connection::sdp::session_description::RTCSessionDescription;
static MAX_MESSAGE: usize = 50;
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub enum ApplicationMessage {
WebRTCPacket(RTCSessionDescription),
@ -60,7 +60,7 @@ pub async fn connect_to_server(
return;
}
let (mut ws_sender, ws_recv) = ws.split();
let (ws_sender, ws_recv) = ws.split();
let to_app: AppSender = to_app_events;
let receiver_is_closed = Arc::new(AtomicBool::new(false));
@ -70,14 +70,29 @@ pub async fn connect_to_server(
listen_to_ws(to_app, moved_copy, ws_recv)
});
while let Ok(msg) = to_core_reciever.recv().await {
tokio::spawn(async move {
send_to_wc(to_core_reciever, receiver_is_closed, ws_sender)
});
info!("Websocket connect successfully");
}
}
}
#[instrument(skip_all)]
async fn send_to_wc(
from_app: AppReceiver,
is_closed: Arc<AtomicBool>,
mut sender: SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, tokio_tungstenite::tungstenite::Message>
) {
while let Ok(msg) = from_app.recv().await {
#[cfg(debug_assertions)]
{
// serialized message
match serde_json::to_string(&msg) {
Err(e) => error!("Could not serialize ApplicationMessage to JSON! {e}"),
Ok(msg) => {
if let Err(e) = ws_sender.send(Message::text(msg)).await {
if let Err(e) = sender.send(Message::text(msg)).await {
error!("Could not send text ApplicationMessage to websocket! Closing websocket\n{e}");
break;
}
@ -91,23 +106,20 @@ pub async fn connect_to_server(
match bincode::serialize(&msg) {
Err(e) => error!("Could not serialize ApplicationMessage into binary! {e}"),
Ok(e) => {
if let Err(e) = ws_sender.send(Message::binary(msg)).await {
if let Err(e) = sender.send(Message::binary(msg)).await {
error!("Could not send binary ApplicationMessage to websocket! Closing websocket\n{e}");
break;
}
}
}
}
}
let _ = ws_sender.close().await;
let _ = sender.close().await;
is_closed.store(true, std::sync::atomic::Ordering::SeqCst);
}
info!("Websocket connect successfully");
}
}
}
#[instrument(skip_all)]