WebSocket text messages
Learn how to send and receive text messages over a WebSocket in Axum, how Utf8Bytes works, and how to build text from formatted strings and JSON
A text message is the most common thing a WebSocket carries. It is a Message::Text variant holding a Utf8Bytes payload, which is a byte buffer with a guarantee: the bytes are always valid UTF-8. UTF-8 is the text encoding the web uses, where ordinary letters take one byte each and other characters take more, and a text message is how a chat line, a notification, or a JSON document travels over the connection. If a connection carries one kind of message, it carries this one.
Where This Fits
The previous page named all five message kinds, and this page takes the first data kind and uses it properly. Text is where most WebSocket programs spend most of their time, and the details matter: how to build a text message from a string, how to read the text back out, and what happens when the bytes are not text at all.
Think of a text message like a postcard. The words are the point, anyone who picks it up can read them, and the post office promises to deliver the words unchanged. A binary message is a sealed parcel by comparison: the contents could be anything, and only the receiver knows what to do with them.
The Smallest Working Version
This server answers every text message with the same text in uppercase, and ignores everything else. The uppercase reply proves the server read the text, changed it, and sent text back.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let Message::Text(text) = msg else { continue };
let reply = text.as_str().to_uppercase();
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", get(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it with cargo run. The verification client sends hello and receives the uppercase reply, as shown in this live run from the scratch project used to verify this chapter:
client: handshake status 101 Switching Protocols
client received: Text(Utf8Bytes(b"hello"))
That output is from the plain echo server, which answers hello with hello. The uppercase server above answers the same message with HELLO, and the shape of the run is identical: 101, then one reply per message, in order.
Working Setup:
If the client sends lowercase text and receives the same text in uppercase, the server read the Utf8Bytes, turned it into a &str, changed it, and sent a new text message back. If the client receives its own text unchanged, the server is echoing instead of transforming, and the reply line is the place to look.
Understanding Utf8Bytes
Utf8Bytes is a wrapper around Bytes that guarantees valid UTF-8, and it is the payload of every text message in Axum 0.8. The guarantee is enforced when the value is built: a Utf8Bytes can only come from a string, which is valid UTF-8 by definition, or from bytes that were checked, through Utf8Bytes::try_from, which fails when the bytes are not valid UTF-8. A program cannot build an invalid Utf8Bytes by accident, and a text message that arrives over the network with invalid bytes is rejected by the protocol layer before the loop ever sees it.
The wrapper behaves like a string in the ways that matter:
let owned: Utf8Bytes = Utf8Bytes::from_static("hello");
let as_str: &str = owned.as_str();
let len = owned.len();
let display = format!("{owned}");
from_static builds a Utf8Bytes from a string that lives for the whole program, such as a literal. as_str returns the contents as a &str, a borrowed string slice. len returns the length in bytes, and format! prints the text through the Display implementation. The wrapper also dereferences to str, which means string methods work directly on it: owned.to_uppercase() returns a String, owned.split_whitespace() splits it into words, and &owned works anywhere a &str is expected. The dereference is automatic, and it is why the smallest version could call text.as_str() and also use text directly in a format string.
Building a Utf8Bytes from an owned string is a conversion, and it works from the three string types a beginner meets:
use axum::extract::ws::Utf8Bytes;
let from_str: Utf8Bytes = "hello".into();
let from_string: Utf8Bytes = String::from("hello").into();
let from_ref: Utf8Bytes = (&String::from("hello")).into();
Going back is just as direct. text.to_string() makes an owned String, text.as_str() borrows a &str, and Bytes::from(text) drops the UTF-8 guarantee and returns the raw bytes, which is useful when the text must be written somewhere that takes bytes.
Utf8Bytes Is Not a String:
Utf8Bytes looks like a string and acts like one in most places, but it is a separate type with its own name. It cannot be assigned to a String variable, and it cannot be passed to a function that takes a String by value. The conversion is always explicit: .to_string() to own it, .as_str() to borrow it, or .into() to build it from a string.
The Concept Behind Text Messages
Text messages exist because most of what programs say to each other is text. A chat line is text, a notification is text, and a JSON document is text. The protocol marks these frames as text so the receiver knows the bytes are readable, and the receiver can display them, log them, or parse them without guessing. The UTF-8 guarantee is what makes that safe: a program that receives a text message never has to ask whether the bytes are readable, because the type system already answered.
The guarantee also draws the line between text and binary. A JSON document sent as text can be parsed as text by any client, including a browser, which is why web applications send JSON over text frames. The same bytes sent as binary would arrive as opaque data, and the client would have to decode them itself. The choice of frame kind is a promise about the contents, and the promise is enforced by the type of the payload.
Why Text Uses Utf8Bytes Instead of String
A String is owned, growable text, and a Utf8Bytes is a reference-counted byte buffer with a UTF-8 promise. The buffer form fits a network library better, because a message can be passed between tasks, split, and stored without copying its bytes, and several owners can share the same buffer cheaply. A String would copy on every move that needed sharing. The buffer also matches the binary side: Binary holds a Bytes, and Text holds a Utf8Bytes, which is a Bytes with a promise, so the two variants share the same underlying machinery. The cost is one conversion at the edges, .into() when building and .as_str() or .to_string() when reading, and the benefit is that moving messages around is cheap.
Building Text Messages
There are three ways to build a text message, and they differ only in what you start from. The constructor takes anything that converts into a Utf8Bytes:
let a = Message::text("hello");
let b = Message::text(String::from("hello"));
let c = Message::text(format!("hello {}", "world"));
Message::text is the usual choice, because it accepts a &str, a String, a formatted string, or a Utf8Bytes directly. The variant form needs the payload already converted:
let d = Message::Text("hello".into());
let e = Message::Text(Utf8Bytes::from_static("hello"));
The From conversion builds the whole message in one step:
let f: Message = "hello".into();
let g: Message = String::from("hello").into();
All five bindings above hold the same value, a Text message with the text hello. The constructor is the most readable when the text is built inline, the variant form is the most explicit when the payload already exists, and the conversion is the shortest when the type is known from context. Use the constructor by default, and reach for the others only when they read better in the surrounding code.
Reading Text Messages
Reading starts with the match arm or the if let, and the binding is a Utf8Bytes:
if let Message::Text(text) = msg {
println!("got: {text}");
println!("length: {}", text.len());
println!("first word: {}", text.as_str().split_whitespace().next().unwrap_or(""));
}
The first line prints the text, the second prints its byte length, and the third prints its first word, or an empty string when there is no word. split_whitespace splits on spaces, tabs, and newlines, and next takes the first piece. unwrap_or("") supplies a fallback for an empty message, because unwrapping the Option would panic on empty input. A text message can be empty, and a loop that panics on empty input closes the connection for a client that sent nothing at all.
Comparing the text with a command is a comparison with a &str, and it works directly, because Utf8Bytes compares equal with strings:
if text.as_str() == "ping" {
let _ = socket.send(Message::text("pong")).await;
}
text == "ping" also works, through the same comparison, but text.as_str() == "ping" is clearer about what is being compared. Either form is fine, and the as_str form is used across this chapter so the comparison is always visible.
A Richer Example With JSON Text
Real applications rarely send bare words. They send structured text, most often JSON, which is a text format for objects with named fields. This example receives a JSON text message, parses it, and answers with a JSON text message. It needs serde and serde_json as dependencies:
[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct ChatIn {
user: String,
text: String,
}
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let Message::Text(text) = msg else { continue };
let parsed: Result<ChatIn, _> = serde_json::from_str(text.as_str());
let reply = match parsed {
Ok(chat) => {
format!("{} says: {}", chat.user, chat.text)
}
Err(_) => "that was not a chat message".to_string(),
};
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", get(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
ChatIn is a struct with two string fields, and #[derive(Deserialize)] teaches serde_json how to fill it from JSON text. serde_json::from_str takes the &str from text.as_str() and returns a Result, which is Ok when the text parses and Err when it does not. The match answers with the chat line on success and with a plain error message on failure, and the connection stays open either way. A client sending {"user": "ada", "text": "hello"} receives ada says: hello, and a client sending not json receives that was not a chat message.
A Bad JSON Message Must Not Close the Connection:
A client that sends broken JSON has made a mistake, not an attack, and the server answers with an error message instead of closing the socket. Returning from the loop on a parse failure would drop every client that sends one malformed message, and the client would have no idea why. Parse errors are answered, not punished.
Variations
Echoing text with a prefix
A prefix marks the reply as the server's own words, which is useful when the client cannot tell its own message from the echo:
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let Message::Text(text) = msg else { continue };
let reply = format!("server got: {text}");
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
A client sending hello receives server got: hello. The format! macro builds the reply, and Message::text takes the resulting String directly, because String converts into Utf8Bytes.
Broadcasting text to a room
A text message can be forwarded to other connections, which is the shape of a chat room. The forwarding uses a broadcast channel, and the full version with a live multi-client run is on the broadcast page. The shape in one connection is a single line: receive the text, then send it into the channel instead of back to the sender.
let _ = tx.send(text.to_string());
text.to_string() turns the Utf8Bytes into an owned String for the channel, because the channel carries strings and the socket's payload belongs to the socket. The broadcast page shows the channel, the subscription, and the send task that carries messages back out.
Sending text from outside the loop
The socket can send at any time, not only in answer to a message. A server that pushes a notification every few seconds spawns a task for the sending side and keeps the receiving side in the loop, which needs the split form of the socket. The split shape is covered on its own page, and the idea to carry forward is that sending and receiving are independent: a reply inside the loop and a push from a timer are the same send call, from different places.
Converting binary to text when it is text
A message that arrives as binary may still hold text, and to_text reads it as text when the bytes are valid UTF-8:
match msg.to_text() {
Ok(text) => println!("read as text: {text}"),
Err(_) => println!("binary was not text"),
}
to_text borrows the message and returns a &str, and it fails when the bytes are not valid UTF-8. It is useful for a server that accepts both frame kinds and treats text the same either way. It is the wrong tool when the kind matters, because it erases the difference between a text frame and a binary frame that happens to hold text.
A Plain Text Diagram of a Text Message
The text travels from the client, through the loop, and back as a new message:
client sends Text("hello")
|
v
recv returns Message::Text(Utf8Bytes)
|
v
text.as_str() gives &str "hello"
|
v
server builds a reply String
|
v
Message::text(reply) builds Text(Utf8Bytes)
|
v
send delivers Text to the client
The conversion happens twice: once from Utf8Bytes to &str on the way in, and once from String to Utf8Bytes on the way out. Both conversions are cheap, and both are where a beginner should look when a type error mentions text.
Testing It
The test below checks the uppercase server and the JSON server in one file. It connects a client, sends hello and expects HELLO, then sends a JSON chat message and expects the formatted line:
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
use futures_util::{SinkExt, StreamExt};
use serde::Deserialize;
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientMessage};
#[derive(Debug, Deserialize)]
struct ChatIn {
user: String,
text: String,
}
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let Message::Text(text) = msg else { continue };
if text.as_str().starts_with('{') {
let parsed: Result<ChatIn, _> = serde_json::from_str(text.as_str());
let reply = match parsed {
Ok(chat) => format!("{} says: {}", chat.user, chat.text),
Err(_) => "that was not a chat message".to_string(),
};
if socket.send(Message::text(reply)).await.is_err() {
return;
}
} else {
let reply = text.as_str().to_uppercase();
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
}
#[tokio::test]
async fn text_uppercase_and_json_chat() {
let app = Router::new().route("/ws", get(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let url = format!("ws://{addr}/ws");
let (mut ws, response) = connect_async(url).await.unwrap();
assert_eq!(response.status(), 101);
ws.send(ClientMessage::Text("hello".into())).await.unwrap();
let msg = ws.next().await.unwrap().unwrap();
assert_eq!(msg, ClientMessage::Text("HELLO".into()));
ws.send(ClientMessage::Text(r#"{"user": "ada", "text": "hello"}"#.into()))
.await
.unwrap();
let msg = ws.next().await.unwrap().unwrap();
assert_eq!(msg, ClientMessage::Text("ada says: hello".into()));
ws.close(None).await.unwrap();
}
Run it with:
cargo test --test text_test
test text_uppercase_and_json_chat ... ok
The test handler routes on the first character: a message starting with { is treated as JSON, and anything else is uppercased. The test asserts both branches, which proves the server reads text, transforms it, and answers with text.
The Test Routes on the First Character:
The starts_with('{') check in the test handler is a shortcut for the test, not a pattern to copy into a real server. A real server decides the message kind from its own protocol, such as a kind field inside the JSON, instead of guessing from the first byte.
Common Beginner Mistakes
Moving the text out and then using it again
// Wrong - text moves into the reply, so the comparison after it fails
let reply = Message::text(text);
if text.as_str() == "ping" {
println!("it was a ping");
}
let _ = socket.send(reply).await;
Message::text(text) takes the Utf8Bytes by value, which moves it into the new message, and the next line tries to use text after the move. The compiler rejects that with a "use of moved value" error. The fix is to order the operations: decide first, then convert. Compare with text.as_str() == "ping" before building the reply, or clone the payload with text.clone() when the same text is genuinely needed in two places. A Utf8Bytes is cheap to clone, because the clone shares the underlying buffer, but the comparison should still come first, because it reads clearer.
Sending a &str directly as a Message
// Wrong - send takes a Message, not a &str
socket.send("hello").await;
send takes a Message, and a &str is not one, so this fails to compile. The fix is socket.send(Message::text("hello")).await, which builds the message first. The same applies to a String: socket.send(reply).await fails, and socket.send(Message::text(reply)).await works. The conversion from a string to a message is explicit, and the compiler error names the expected type.
Assuming the text is never empty
// Wrong - an empty message makes this panic
let first = text.as_str().chars().next().unwrap();
A text message can be empty, and chars().next() returns None for it. Unwrapping that None panics the connection task. The fix is unwrap_or(' ') with a fallback character, or a match on the Option, or a check with text.is_empty() before reading. Empty messages are legal, and a loop must treat them as ordinary input.
Parsing JSON with unwrap
// Wrong - one malformed message panics the connection task
let chat: ChatIn = serde_json::from_str(text.as_str()).unwrap();
A client can send any text, including text that is not JSON, and from_str returns an Err for it. Unwrapping turns a client mistake into a server panic. The fix is the match on the Result from the richer example, which answers with an error message and keeps the connection open. Parse failures are data, not disasters.
Treating text as bytes and bytes as text
// Wrong - into_data on a text message returns the bytes, not the text
let bytes = msg.into_data();
let reply = format!("got {} bytes", bytes.len());
This compiles and runs, but it answers a text message with a byte count, which is not what the client asked for. The mistake is using the byte conversion when the text conversion was meant. into_data is for when the bytes are the point, and to_text or the Text arm is for when the words are the point. Pick the conversion that matches the question being asked.
Final Complete Example
Here is everything from this page put together: the uppercase answer, the JSON chat answer, and the test that proves both.
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct ChatIn {
user: String,
text: String,
}
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let Message::Text(text) = msg else { continue };
let reply = if text.as_str().starts_with('{') {
match serde_json::from_str::<ChatIn>(text.as_str()) {
Ok(chat) => format!("{} says: {}", chat.user, chat.text),
Err(_) => "that was not a chat message".to_string(),
}
} else {
text.as_str().to_uppercase()
};
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", get(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the checks with these commands:
cargo check
cargo test --test text_test
cargo run
Summary
A text message is a Text variant with a Utf8Bytes payload, and the whole page is a set of conversions around that fact: strings become Utf8Bytes through .into(), Utf8Bytes becomes a &str through .as_str(), and a &str becomes a message through Message::text. The guarantee behind the type is what makes text safe to display, log, and parse, and the loop's job is to decide what the words mean and answer in kind. The decision to carry forward is to parse text as text: read the words with as_str, decide with a match or a comparison, and answer with a new text message, while a message that fails to parse gets an answer, not a closed connection. The next page takes the other data kind, binary, where the bytes carry no promise at all.