user struct

This commit is contained in:
Adam 2024-07-16 20:49:24 -04:00
parent 822c9606ce
commit a719e78001

View file

@ -20,7 +20,12 @@ fn greeting(state: &Arc<AppState>) -> String {
)
}
pub async fn websocket(stream: WebSocket, state: Arc<AppState>, who: SocketAddr) {
pub struct User {
name: String,
addr: SocketAddr,
}
pub async fn websocket(stream: WebSocket, state: Arc<AppState>, who: User) {
// By splitting, we can send and receive at the same time.
let (mut sender, mut receiver) = stream.split();
@ -31,7 +36,7 @@ pub async fn websocket(stream: WebSocket, state: Arc<AppState>, who: SocketAddr)
let mut rx = state.tx.subscribe();
// ANNOUNCE THY PRESENCE
let msg = format!("{who} joined.");
let msg = format!("{} joined.", who.name);
tracing::debug!("{msg}");
let _ = state.tx.send(msg);
@ -47,7 +52,7 @@ pub async fn websocket(stream: WebSocket, state: Arc<AppState>, who: SocketAddr)
// handle new incoming messages
let mut recv_task = tokio::spawn(async move {
while let Some(Ok(message)) = receiver.next().await {
message_handler(message, &state, who).await
message_handler(message, &state, who.addr).await
}
});
@ -65,5 +70,14 @@ pub async fn websocket_handler(
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
tracing::debug!("New connection from {addr}");
ws.on_upgrade(move |socket| websocket(socket, state, addr))
ws.on_upgrade(move |socket| {
websocket(
socket,
state,
User {
name: "Anonymous".to_string(),
addr,
},
)
})
}