message handling

This commit is contained in:
Adam 2024-07-24 19:21:16 -04:00
parent 5dffc94ea1
commit d31f790e81
3 changed files with 23 additions and 9 deletions

View file

@ -21,16 +21,19 @@ pub fn Chat() -> impl IntoView {
create_effect(move |_| {
websocket.ready_state.with(move |state| match *state {
ConnectionReadyState::Connecting => {
update_chat_history(&set_chat_history, format!("Connecting to game server...\n"));
update_chat_history(
&set_chat_history,
"Connecting to game server...\n".to_string(),
);
}
ConnectionReadyState::Open => {
update_chat_history(&set_chat_history, format!("Connected!\n"));
update_chat_history(&set_chat_history, "Connected!\n".to_string());
}
ConnectionReadyState::Closing => {
update_chat_history(&set_chat_history, format!("Disconnecting...\n"));
update_chat_history(&set_chat_history, "Disconnecting...\n".to_string());
}
ConnectionReadyState::Closed => {
update_chat_history(&set_chat_history, format!("Disconnected.\n"));
update_chat_history(&set_chat_history, "Disconnected.\n".to_string());
}
})
});
@ -48,7 +51,9 @@ pub fn Chat() -> impl IntoView {
if let Some(message) = message_raw {
if let Ok(_game) = serde_json::from_str::<Game>(message) {
logging::log!("Game object received at chat component");
} else if let Ok(_) = serde_json::from_str::<ServerStateSummary>(message) {
} else if let Ok(_state_summary) =
serde_json::from_str::<ServerStateSummary>(message)
{
logging::log!("State Summary received at chat component");
} else {
update_chat_history(&set_chat_history, format!("{}\n", message));
@ -58,7 +63,9 @@ pub fn Chat() -> impl IntoView {
});
let send_message = move |_| {
websocket.send(&chat_input_ref.get().unwrap().value());
websocket.send(&serde_json::to_string(&ChatMessage {
text: chat_input_ref.get().unwrap().value(),
}).unwrap());
chat_input_ref.get().unwrap().set_value("");
logging::log!("Send Message");
};

View file

@ -1,6 +1,12 @@
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
/// Chat message
#[derive(Serialize, Deserialize, Debug)]
pub struct ChatMessage {
pub text: String,
}
/// Server state summary
#[derive(Serialize, Deserialize, Debug)]
pub struct ServerStateSummary {

View file

@ -24,11 +24,12 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User
} else {
let _res = tx.send(String::from("error creating game"));
}
} else {
// just echo
let msg = format! {"{0}: {1}", who.name, text};
} else if let Ok(chat_message) = serde_json::from_str::<ChatMessage>(&text) {
let msg = format! {"{0}: {1}", who.name, chat_message.text};
tracing::debug!("{msg}");
let _res = tx.send(msg);
} else {
tracing::debug!("Unhandled message: {}", &text);
}
}