WebSocket binary messages

Learn how to send and receive binary messages over a WebSocket in Axum, how Bytes works, and when binary fits better than text

A binary message is a Message::Binary variant holding a Bytes payload, which is a buffer of raw bytes with no promise about what they mean. The bytes could be an image fragment, a compressed chunk, a serialized structure, or any data that is not text. The server does not interpret them, and it does not need to. Binary is the frame kind for data that is not meant to be read as words.

Where This Fits

The previous page covered text, where the bytes carry a promise that they are readable. This page covers the other data kind, where the bytes carry no promise at all. The two kinds travel over the same connection and through the same loop, and the server tells them apart with the match. A program that only ever sends text never needs this page, and a program that sends files, images, or packed data needs nothing else.

Think of a binary message like a sealed parcel. The label says how heavy it is, not what is inside, and only the receiver knows whether it holds a photograph, a sound clip, or a packed box of numbers. A text message is a postcard by comparison: anyone can read it, and the contents are the point.

The Smallest Working Version

This server answers every binary message with a text message reporting the byte count and the first byte. The answer is text, because the count is a readable fact, even though the input was binary.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
bytes = "1"
src/main.rs
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::Binary(data) = msg else { continue };
        let first = data.first().copied().unwrap_or(0);
        let reply = format!("bytes: {}, first: {}", data.len(), first);
        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 live run below comes from the scratch project used to verify this chapter, where the client sent the five bytes 0, 1, 2, 3, 255 to an echo server on port 3001:

client: handshake status 101 Switching Protocols
client received binary: Binary(b"\0\x01\x02\x03\xff")

The echo server sent the same five bytes back unchanged, including the zero byte and the 255 byte, which are not valid text. That round trip is the proof that binary frames carry arbitrary bytes without mangling them. The counting server above would answer the same five bytes with bytes: 5, first: 0.

Working Setup:

If the client receives its exact bytes back, including zero bytes and bytes above 127, the binary path works. If a byte changes value on the round trip, the message is being treated as text somewhere, and the match arm is the place to look.

Understanding Bytes

Bytes is a reference-counted byte buffer from the bytes crate, and it is the payload of every binary message in Axum 0.8. It is also the payload of ping and pong frames, and the raw form of a text payload once the UTF-8 promise is dropped. A Bytes value owns its data, can be shared cheaply between tasks, and can be sliced without copying.

The operations a beginner needs are few:

let data = Bytes::from_static(b"hello");
let len = data.len();
let first = data.first().copied().unwrap_or(0);
let slice = &data[1..3];
let vec: Vec<u8> = data.to_vec();
let empty = data.is_empty();

from_static builds a Bytes from bytes that live for the whole program, such as a byte string literal. len returns the byte count, first returns the first byte as an Option, and indexing with a range returns a slice of the buffer. to_vec copies the bytes into a Vec<u8>, which is the owned, growable byte list from the standard library. is_empty reports whether the buffer holds nothing. Slicing a Bytes is cheap, because the slice shares the underlying storage, and to_vec is the step that copies, so it is used only when an owned copy is genuinely needed.

Bytes converts into and out of the other byte types without fuss:

use bytes::Bytes;

let from_vec: Bytes = vec![1u8, 2, 3].into();
let from_slice: Bytes = Bytes::copy_from_slice(&[1u8, 2, 3]);
let from_static: Bytes = Bytes::from_static(b"data");
let back_to_vec: Vec<u8> = from_vec.to_vec();

copy_from_slice copies from a slice, from_static borrows a static slice without copying, and .into() converts a Vec<u8> by taking over its storage without copying. The last point matters for performance: a Vec<u8> that becomes a Bytes through .into() does not copy its bytes, it just changes hands.

Bytes Is Shared, Vec Is Owned:

A Bytes can be cloned cheaply, because the clone shares the same storage and only bumps a reference count. A Vec<u8> clone copies every byte. That is why network code passes Bytes around and converts to Vec<u8> only at the edges, where an owned, mutable list is needed.

The Concept Behind Binary Messages

Binary messages exist because not all data is text. An image is bytes, a sound clip is bytes, a compressed file is bytes, and a serialized structure is bytes. Forcing those through a text frame would require encoding them as text first, which costs time and space, and the receiver would have to decode them back. A binary frame skips both steps: the bytes travel as they are, and the receiver interprets them with whatever format the application agreed on.

The agreement is the application's business, not the protocol's. The WebSocket standard says nothing about what binary bytes mean. Two programs that exchange binary messages must agree beforehand on the format, a first byte that names the kind, a length prefix, or a fixed layout. The server in the smallest version does not interpret the bytes at all: it counts them and reads the first one, which is the most a server can do without knowing the format.

Why Binary Uses Bytes Instead of Vec

A Vec<u8> is the standard owned byte list, and it would work as a payload. Bytes is used instead for the same reason text uses Utf8Bytes: sharing without copying. A binary message can be forwarded to several connections, stored in a buffer, and sliced into pieces, and each of those steps with a Vec<u8> would copy the data. With Bytes, the clone shares the storage, and the slice shares it too. The conversion at the edges is one call, .into() when building and .to_vec() when an owned list is needed, and the machinery in between stays cheap.

Building Binary Messages

The constructor takes anything that converts into a Bytes:

let a = Message::binary(vec![1u8, 2, 3]);
let b = Message::binary(Bytes::from_static(b"data"));
let c = Message::binary(Bytes::copy_from_slice(&[9u8, 8, 7]));

Message::binary is the usual choice. The variant form needs the payload already converted:

let d = Message::Binary(vec![1u8, 2, 3].into());
let e = Message::Binary(Bytes::from_static(b"data"));

The From conversion builds the whole message in one step:

let f: Message = vec![1u8, 2, 3].into();
let g: Message = Bytes::from_static(b"data").into();
let h: Message = b"raw".as_slice().into();

A Vec<u8>, a Bytes, and a &[u8] slice all become Binary through conversion. All of the bindings above hold binary messages, and the choice between them is the same as for text: the constructor by default, the variant form when the payload already exists, and the conversion when the type is known from context.

Reading Binary Messages

Reading starts with the Binary arm, and the binding is a Bytes:

if let Message::Binary(data) = msg {
    println!("got {} bytes", data.len());
    println!("first byte: {}", data.first().copied().unwrap_or(0));
    println!("all bytes: {:?}", data.to_vec());
}

The first line prints the count, the second prints the first byte with a fallback of 0 for an empty message, and the third prints the whole buffer as a list of numbers. data.first() returns an Option, because the message can be empty, and copied turns the borrowed byte into an owned one. An empty binary message is legal, and a loop that unwraps the first byte panics on it, so the fallback is part of the pattern.

A binary message can be answered with binary, with text, or with nothing at all. Echoing binary back is the same shape as echoing text:

if socket.send(Message::Binary(data)).await.is_err() {
    return;
}

The data moves into the new message, which is why the binding is used once. When the bytes are needed twice, for logging and for echoing, clone the Bytes first: socket.send(Message::Binary(data.clone())) shares the storage, so the clone is cheap.

A Richer Example With a Tiny Binary Format

A real binary protocol needs a format, and the smallest useful one is a kind byte followed by a payload. This example defines two kinds: kind 1 is a counter that the server increments and sends back as binary, and kind 2 is a chunk that the server counts and answers with text. Anything else gets a text error:

src/main.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};
use bytes::Bytes;

async fn ws_handler(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(handle_socket)
}

async fn handle_socket(mut socket: WebSocket) {
    let mut counter: u32 = 0;
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        let Message::Binary(data) = msg else { continue };
        let Some((&kind, _payload)) = data.split_first() else {
            continue;
        };
        match kind {
            1 => {
                counter += 1;
                let reply = Bytes::copy_from_slice(&counter.to_be_bytes());
                if socket.send(Message::Binary(reply)).await.is_err() {
                    return;
                }
            }
            2 => {
                let reply = format!("chunk bytes: {}", data.len() - 1);
                if socket.send(Message::text(reply)).await.is_err() {
                    return;
                }
            }
            _ => {
                let reply = format!("unknown kind: {kind}");
                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();
}

split_first splits the buffer into its first byte and the rest, returning None for an empty message, which the let ... else { continue } skips. Kind 1 ignores the payload, increments a counter kept in the loop, and answers with the counter as four bytes in big-endian order, which is the standard network byte order where the most significant byte comes first. to_be_bytes produces those four bytes, and Bytes::copy_from_slice wraps them. Kind 2 answers with a text message reporting the payload length, which is the total length minus the kind byte. The counter lives in the callback, so each connection has its own counter, and a new connection starts again at zero.

The First Byte Is a Convention, Not a Rule:

The kind byte in this example is an agreement between this server and its clients, not something the WebSocket standard defines. A client that does not know the agreement sends bytes the server cannot interpret, and the server answers with an error instead of guessing. Document the format next to the code that implements it, because a format that lives only in one programmer's head breaks the first time someone else writes a client.

Variations

Echoing binary unchanged

The echo shape is the same as for text, with the variant swapped:

src/main.rs
async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        if socket.send(msg).await.is_err() {
            return;
        }
    }
}

Sending the whole msg back echoes text as text and binary as binary, because the message keeps its kind. That is why the echo server from the first pages works for both kinds without a match at all. A loop that echoes the message itself never needs to know what kind it is.

Treating binary as text when it is text

A binary message may 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. The failure is the point: binary that is not text must not be printed as text, because the output would be garbage. The match keeps the two cases apart, and the error arm is where the server decides what non-text binary means for it.

Reading a number out of binary

A binary message that holds a number in big-endian order is read with the matching conversion:

if data.len() >= 4 {
    let bytes: [u8; 4] = data[0..4].try_into().unwrap();
    let number = u32::from_be_bytes(bytes);
    println!("number: {number}");
}

data[0..4] slices the first four bytes, try_into turns the slice into a four-byte array, and from_be_bytes interprets the array as a big-endian number. The length check matters: slicing four bytes out of a shorter message panics, so the if guards it. The unwrap on try_into is safe here only because the length check already proved the slice has four bytes, and a comment saying so would help the next reader.

Sending binary from outside the loop

A server that pushes binary data, such as a file chunk or a sensor reading, sends from a spawned task while the loop keeps receiving, which needs the split form of the socket. The split shape is covered on its own page, and the sending call is the same Message::binary used inside the loop.

When Binary Fits Better Than Text

Binary fits when the data is not text, when the data is large and encoding it as text would waste space, or when the format is fixed and both sides know it. A file upload over a WebSocket, a game state update packed into bytes, or a sensor stream of numbers are binary jobs. Text fits when a human might read the message, when the message is JSON, or when a browser client must parse it without a decoder. A chat message is text, and a photograph is binary, and a server that mixes the two up pays for the confusion in encoding code that should not exist.

JSON Over Binary Is a Choice, Not a Mistake:

A program can send JSON bytes in a binary frame, and some do, to mark the message as machine data rather than human text. The bytes are the same, and the parsing is the same. The frame kind is a label, and the label should match what the receiver expects. A browser client that expects text frames will not parse a binary frame as JSON without extra code, so the label and the client must agree.

A Plain Text Diagram of a Binary Message

The bytes travel from the client, through the loop, and back as a new message:

client sends Binary([0, 1, 2, 3, 255])
        |
        v
recv returns Message::Binary(Bytes)
        |
        v
data.len() gives 5, data.first() gives 0
        |
        v
server builds a reply, binary or text
        |
        v
send delivers the reply to the client

No conversion to text happens on the way in, and none is needed on the way out. The bytes are read as bytes, counted as bytes, and answered as bytes or as a text fact about the bytes.

Testing It

The test below checks the echo and the counting server in one file. It sends five binary bytes and expects the same five back, then sends a kind 2 chunk and expects the text count:

Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
tests/binary_test.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};
use bytes::Bytes;
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientMessage};

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::Binary(data) = msg else { continue };
        if data.first().copied() == Some(2) {
            let reply = format!("chunk bytes: {}", data.len() - 1);
            if socket.send(Message::text(reply)).await.is_err() {
                return;
            }
        } else if socket.send(Message::Binary(data)).await.is_err() {
            return;
        }
    }
}

#[tokio::test]
async fn binary_echo_and_chunk_count() {
    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::Binary(vec![0u8, 1, 2, 3, 255].into()))
        .await
        .unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    assert_eq!(msg, ClientMessage::Binary(vec![0u8, 1, 2, 3, 255].into()));
    ws.send(ClientMessage::Binary(vec![2u8, 10, 20, 30].into()))
        .await
        .unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    assert_eq!(msg, ClientMessage::Text("chunk bytes: 3".into()));
    ws.close(None).await.unwrap();
}

Run it with:

cargo test --test binary_test
test binary_echo_and_chunk_count ... ok

The first assertion proves the five bytes came back unchanged, including the zero and the 255. The second proves the server read the kind byte, counted the three payload bytes, and answered with text.

Common Beginner Mistakes

Printing binary as text

// Wrong - binary bytes are not text, and printing them as text shows garbage
if let Message::Binary(data) = msg {
    let text = String::from_utf8_lossy(&data);
    println!("{text}");
}

from_utf8_lossy replaces invalid bytes with a replacement character, so the output looks like text with holes in it, and the information is gone. The fix is to print the bytes as numbers, with {:?} on the Vec<u8> from data.to_vec(), or to count them and log the count. Binary is logged as numbers, not as words.

Unwrapping the first byte of an empty message

// Wrong - an empty binary message makes this panic
let first = data[0];

Indexing data[0] panics when the message is empty, because there is no first byte. The fix is data.first().copied().unwrap_or(0), which supplies a fallback, or a length check before indexing. Empty binary messages are legal, and a loop must treat them as ordinary input.

Converting binary to a String with unwrap

// Wrong - binary data is often not valid UTF-8
let text = String::from_utf8(data.to_vec()).unwrap();

from_utf8 fails when the bytes are not valid UTF-8, and unwrapping that failure panics the connection task for a message that is perfectly legal. The fix is to match on the result, or to use to_text and handle the error, or to keep the data as bytes and never convert it. A conversion that can fail must be handled, not unwrapped.

Cloning a Vec when Bytes would share

// Wrong - copying the bytes to echo them
if let Message::Binary(data) = msg {
    let owned: Vec<u8> = data.to_vec();
    let _ = socket.send(Message::binary(owned)).await;
}

This works, and it copies every byte twice: once into the Vec and once into the new Bytes. The fix is to send the Bytes directly, socket.send(Message::Binary(data)).await, which moves the buffer without copying. The copy only matters for large messages, but the direct form is also shorter, so there is no reason to keep the copy.

Assuming binary and text are interchangeable

// Wrong - a text client cannot read a binary reply
let reply = Message::binary(Bytes::from_static(b"hello"));
let _ = socket.send(reply).await;

A client that expects text frames receives a binary frame with the word hello inside, and a browser client will not display it as text. The fix is to match the reply kind to the request kind, or to the client's expectation: text answers for text requests, binary answers for binary requests, unless the two sides agreed otherwise. The frame kind is part of the answer, not decoration.

Final Complete Example

Here is everything from this page put together: the kind-byte protocol with its counter and chunk counting, and the test that proves the echo and the count.

src/main.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};
use bytes::Bytes;

async fn ws_handler(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(handle_socket)
}

async fn handle_socket(mut socket: WebSocket) {
    let mut counter: u32 = 0;
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        let Message::Binary(data) = msg else { continue };
        let Some((&kind, _payload)) = data.split_first() else {
            continue;
        };
        match kind {
            1 => {
                counter += 1;
                let reply = Bytes::copy_from_slice(&counter.to_be_bytes());
                if socket.send(Message::Binary(reply)).await.is_err() {
                    return;
                }
            }
            2 => {
                let reply = format!("chunk bytes: {}", data.len() - 1);
                if socket.send(Message::text(reply)).await.is_err() {
                    return;
                }
            }
            _ => {
                let reply = format!("unknown kind: {kind}");
                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 binary_test
cargo run

Summary

A binary message is a Binary variant with a Bytes payload, and the whole page is a set of rules around that fact: bytes are read as bytes, counted as bytes, and answered as bytes or as a text fact about the bytes, with no conversion to text unless the bytes are known to be text. The format of the bytes is the application's agreement, and the smallest useful agreement is a kind byte followed by a payload. The decision to carry forward is to match the frame kind to the data: text for words and JSON, binary for files, images, and packed numbers, and the wrong kind is a bug that shows up on the client, not on the server. The next two pages take the control kinds, starting with ping and pong, the frames that keep a connection alive.