Skip to content
Myr

main.rs

This file

Path

examples/chat/src/main.rs

161 lines · 5.0 KiB · Rust

Last changed by

Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7

History of this file

Take it

1//! Example chat application.2//!3//! Run with4//!5//! ```not_rust6//! cargo run -p example-chat7//! ```89use axum::{10    extract::{11        ws::{Message, Utf8Bytes, WebSocket, WebSocketUpgrade},12        State,13    },14    response::{Html, IntoResponse},15    routing::get,16    Router,17};18use futures_util::{sink::SinkExt, stream::StreamExt};19use std::{20    collections::HashSet,21    sync::{Arc, Mutex},22};23use tokio::sync::broadcast;24use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};2526// Our shared state27struct AppState {28    // We require unique usernames. This tracks which usernames have been taken.29    user_set: Mutex<HashSet<String>>,30    // Channel used to send messages to all connected clients.31    tx: broadcast::Sender<String>,32}3334#[tokio::main]35async fn main() {36    tracing_subscriber::registry()37        .with(38            tracing_subscriber::EnvFilter::try_from_default_env()39                .unwrap_or_else(|_| format!("{}=trace", env!("CARGO_CRATE_NAME")).into()),40        )41        .with(tracing_subscriber::fmt::layer())42        .init();4344    // Set up application state for use with with_state().45    let user_set = Mutex::new(HashSet::new());46    let (tx, _rx) = broadcast::channel(100);4748    let app_state = Arc::new(AppState { user_set, tx });4950    let app = Router::new()51        .route("/", get(index))52        .route("/websocket", get(websocket_handler))53        .with_state(app_state);5455    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")56        .await57        .unwrap();58    tracing::debug!("listening on {}", listener.local_addr().unwrap());59    axum::serve(listener, app).await;60}6162async fn websocket_handler(63    ws: WebSocketUpgrade,64    State(state): State<Arc<AppState>>,65) -> impl IntoResponse {66    ws.on_upgrade(|socket| websocket(socket, state))67}6869// This function deals with a single websocket connection, i.e., a single70// connected client / user, for which we will spawn two independent tasks (for71// receiving / sending chat messages).72async fn websocket(stream: WebSocket, state: Arc<AppState>) {73    // By splitting, we can send and receive at the same time.74    let (mut sender, mut receiver) = stream.split();7576    // Username gets set in the receive loop, if it's valid.77    let mut username = String::new();78    // Loop until a text message is found.79    while let Some(Ok(message)) = receiver.next().await {80        if let Message::Text(name) = message {81            // If username that is sent by client is not taken, fill username string.82            check_username(&state, &mut username, name.as_str());8384            // If not empty we want to quit the loop else we want to quit function.85            if !username.is_empty() {86                break;87            } else {88                // Only send our client that username is taken.89                let _ = sender90                    .send(Message::Text(Utf8Bytes::from_static(91                        "Username already taken.",92                    )))93                    .await;9495                return;96            }97        }98    }99100    // We subscribe *before* sending the "joined" message, so that we will also101    // display it to our client.102    let mut rx = state.tx.subscribe();103104    // Now send the "joined" message to all subscribers.105    let msg = format!("{username} joined.");106    tracing::debug!("{msg}");107    let _ = state.tx.send(msg);108109    // Spawn the first task that will receive broadcast messages and send text110    // messages over the websocket to our client.111    let mut send_task = tokio::spawn(async move {112        while let Ok(msg) = rx.recv().await {113            // In any websocket error, break loop.114            if sender.send(Message::text(msg)).await.is_err() {115                break;116            }117        }118    });119120    // Clone things we want to pass (move) to the receiving task.121    let tx = state.tx.clone();122    let name = username.clone();123124    // Spawn a task that takes messages from the websocket, prepends the user125    // name, and sends them to all broadcast subscribers.126    let mut recv_task = tokio::spawn(async move {127        while let Some(Ok(Message::Text(text))) = receiver.next().await {128            // Add username before message.129            let _ = tx.send(format!("{name}: {text}"));130        }131    });132133    // If any one of the tasks run to completion, we abort the other.134    tokio::select! {135        _ = &mut send_task => recv_task.abort(),136        _ = &mut recv_task => send_task.abort(),137    };138139    // Send "user left" message (similar to "joined" above).140    let msg = format!("{username} left.");141    tracing::debug!("{msg}");142    let _ = state.tx.send(msg);143144    // Remove username from map so new clients can take it again.145    state.user_set.lock().unwrap().remove(&username);146}147148fn check_username(state: &AppState, string: &mut String, name: &str) {149    let mut user_set = state.user_set.lock().unwrap();150151    if !user_set.contains(name) {152        user_set.insert(name.to_owned());153154        string.push_str(name);155    }156}157158// Include utf-8 file at **compile** time.159async fn index() -> Html<&'static str> {160    Html(std::include_str!("../chat.html"))161}