Server: Add basic send message

This commit is contained in:
Leon Grünewald 2024-06-02 12:42:08 +02:00
parent c14f3c4558
commit 886c2efe5d
2 changed files with 57 additions and 23 deletions

View file

@ -1,6 +1,9 @@
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum Message {
Text { chat: (), content: String }
}

View file

@ -5,7 +5,7 @@ use std::{net::SocketAddr, sync::Arc};
use tokio::{net::{TcpListener, TcpStream}, sync::Mutex};
use crate::config::Config;
use figment::{Figment, providers::{Format, Env, Json}};
use futures_util::{StreamExt, stream::SplitSink, TryStreamExt, };
use futures_util::{StreamExt, stream::SplitSink, TryStreamExt, SinkExt};
use tokio_tungstenite::{WebSocketStream, tungstenite::Message as TungsteniteMessage};
use common::packets::Message;
@ -49,7 +49,7 @@ async fn handle_connection(stream: TcpStream, addr: SocketAddr, peer_list: PeerL
.await
.expect("Could not initialize websocket stream");
let (mut websocket_tx, mut websocket_rx) = websocket_stream.split();
let (websocket_tx, mut websocket_rx) = websocket_stream.split();
{
let mut locked_peer_list = peer_list.lock().await;
@ -59,22 +59,7 @@ async fn handle_connection(stream: TcpStream, addr: SocketAddr, peer_list: PeerL
while let Some(socket_result) = websocket_rx.next().await {
match socket_result {
Ok(websocket_message) => {
match websocket_message {
TungsteniteMessage::Text(text_message) => {
match serde_json::from_str(&text_message) {
Ok(message) => {
handle_message(message, addr, peer_list.clone())
}
Err(err) => {
eprintln!("ParseError: {err}")
}
}
}
_ => {
println!("Websocket: Unsupported message type");
}
}
handle_websocket_message(websocket_message, addr, peer_list.clone()).await;
}
Err(err) => {
eprintln!("SocketError: {err}");
@ -84,10 +69,56 @@ async fn handle_connection(stream: TcpStream, addr: SocketAddr, peer_list: PeerL
}
}
fn handle_message(message: Message, sender: SocketAddr, peer_list: PeerList) {
match message {
async fn handle_websocket_message(websocket_message: TungsteniteMessage, addr: SocketAddr, peer_list: PeerList) {
match websocket_message {
TungsteniteMessage::Text(text_message) => {
match serde_json::from_str(&text_message) {
Ok(message) => {
if let Err(err) = handle_message(message, addr, peer_list.clone()).await {
eprintln!("Handle message error: {err}");
}
}
Err(err) => {
eprintln!("ParseError: {err}")
}
}
}
TungsteniteMessage::Close(_) => {
let mut locked_peer_list = peer_list.lock().await;
for i in 0..locked_peer_list.len() {
if locked_peer_list[i].addr.to_string() == addr.to_string() {
locked_peer_list.remove(i);
break;
}
}
}
_ => {
println!("Websocket: Unsupported message type");
}
}
}
async fn handle_message(message: Message, sender: SocketAddr, peer_list: PeerList) -> anyhow::Result<()> {
match &message {
Message::Text { chat, content} => {
println!("{chat}: {content}")
let mut use_peer_list = peer_list.lock().await;
for mut peer in &mut *use_peer_list {
println!("[Message]{}: {content}", peer.addr.to_string());
if peer.addr.to_string() == sender.to_string() {
continue;
}
peer.websocket_tx.send(
tokio_tungstenite::tungstenite::Message::Text(
serde_json::to_string(&message)?
)
).await?;
}
}
}
Ok(())
}