expression
WebSocket: recognize ping, pong and close
Control messages support connection maintenance and closure rather than application data. Axum handles automatic ping responses; the following model only classifies message values, not actual traffic. Standalone synthetic example. Expected stdout (not executed): ping pong close Common mistake: Treating a ping as a chat message or assuming a pong proves application health.
Formal Syntax & Structure
rust syntaxrust
match message { Message::Ping(..), Message::Pong(..), Message::Close(..), .. }Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}, response::{IntoResponse, sse::{Event, Sse}}, extract::ws::{Message, WebSocketUpgrade, WebSocket}};use std::convert::Infallible;use futures_util::stream;use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { for msg in [Message::Ping(vec![1].into()), Message::Pong(vec![1].into()), Message::Close(None)] { let label = match msg { Message::Ping(_) => "ping", Message::Pong(_) => "pong", Message::Close(_) => "close", _ => "data", }; println!("{label}"); }}