WebSocket Close frame

Learn how the WebSocket close frame works in Axum, what CloseFrame holds, how the graceful close handshake runs, and why the socket must be drained after a close

A close frame is a control frame that says "this connection is ending", and it is how a WebSocket closes on purpose instead of fading away. It is a Message::Close variant holding an optional CloseFrame, which carries a numeric code and a short text reason. The handshake around it has four steps, and the step beginners miss is the last one: after receiving a close frame, the server must keep reading until the socket ends, so the automatic close reply is actually sent. A server that returns immediately drops the connection before the reply goes out, and the client sees an error instead of a clean close.

Where This Fits

The previous page covered ping and pong, the frames that keep a connection alive. This page covers the frame that ends one. Every connection ends eventually, and the difference between a clean ending and a broken one is this frame and the few lines of code around it.

Think of a close frame like saying goodbye at the end of a phone call. One side says "I have to go", the other side says "goodbye", and then both hang up. A connection that just goes silent is a call where the line went dead mid-sentence: nobody knows whether the other side heard the last words. The close frame is the goodbye, and the handshake is the exchange of goodbyes.

The Smallest Working Version

This server echoes text, logs the close frame when it arrives, drains the socket so the automatic reply is flushed, and then returns. The drain loop is the whole lesson of this page, and it is three lines long.

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

[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
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 };
        match msg {
            Message::Text(text) => {
                if socket.send(Message::Text(text)).await.is_err() {
                    return;
                }
            }
            Message::Close(frame) => {
                println!("got close: {frame:?}");
                while let Some(msg) = socket.recv().await {
                    match msg {
                        Ok(other) => println!("while draining: {other:?}"),
                        Err(error) => {
                            println!("drain ended: {error}");
                            break;
                        }
                    }
                }
                println!("drain done, returning");
                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 runs below come from the scratch project used to verify this chapter, where a tokio-tungstenite client sent a text message, then a close frame with code 1000 and the reason done. First, the version without the drain, which returns immediately on the close:

client sent close frame (code 1000, reason done)
client stream error after close: WebSocket protocol error: Connection reset without closing handshake

The client expected a close reply and got a reset instead, because the server dropped the socket before the queued reply was flushed. Then the version with the drain, from the same client against the draining server:

client sent close frame (code 1000, reason done)
client received after close: Close(Some(CloseFrame { code: Normal, reason: Utf8Bytes(b"done") }))

And on the server side:

close server got close: Some((1000, "done"))
close server: draining socket so the queued reply is flushed
close server: drain done, returning

The client received the close reply with the same code and reason, and the stream ended cleanly afterwards. The only difference between the two runs is the drain loop, and the difference in outcome is a clean close against a protocol error.

Working Setup:

If the client receives a Close message back after sending one, and the stream ends without an error, the drain worked. If the client reports "Connection reset without closing handshake", the handler returned before the reply was flushed, and the drain loop is missing.

Understanding CloseFrame

A CloseFrame is a small struct with two public fields, and its shape in Axum 0.8.9 is:

pub struct CloseFrame {
    pub code: CloseCode,
    pub reason: Utf8Bytes,
}

code has type CloseCode, which in Axum 0.8.9 is a plain alias for u16, a 16-bit number. reason is a Utf8Bytes, the same text payload type as a text message, holding a short human-readable note. The Message::Close variant wraps the frame in an Option, because a peer may close without giving a code or a reason at all:

Message::Close(Some(frame)) => {
    println!("code: {}, reason: {}", frame.code, frame.reason);
}
Message::Close(None) => {
    println!("closed without a code or reason");
}

The first arm prints the code and the reason from a frame that has them. The second arm handles the bare close, which is common: many clients send Close(None), and the server must treat it as a normal close, not as an error. The two arms together cover every close the loop can receive.

The Close Codes

The code is a number from a standard list, and the common ones are:

CodeMeaning
1000Normal closure, the purpose of the connection is fulfilled
1001Going away, the server is going down or the browser navigated away
1002Protocol error, the other side broke the rules
1003Unsupported data, the other side sent a kind this endpoint cannot accept
1006Abnormal closure, the connection dropped without a close frame
1007Invalid payload, the data did not fit the message kind
1008Policy violation, the message broke a rule this endpoint enforces
1009Message too big, the message was larger than this endpoint accepts
1011Internal error, the server hit an unexpected problem

Code 1000 is the normal one, and it is what a client sends when it is done. Code 1001 is what a browser sends when the user navigates away. Code 1006 is special: it is never sent in a frame, it is the code a program reports when the connection died without any close frame at all, which is exactly what the client saw in the first live run above. The codes from 4000 upward are free for applications to define, so a program can close with code 4001 to mean something of its own, as long as both sides agree on the meaning.

The Code Is a Number, Not an Enum:

In Axum 0.8.9, CloseCode is a type alias for u16, so a close frame is built with a plain number such as 1000. The underlying tungstenite crate has its own CloseCode enum with variants such as Normal, but the Axum frame does not use it. A client built on tokio-tungstenite prints the code as Normal for 1000, which is the same value under a different name.

The Concept Behind the Graceful Close

The graceful close has four steps, and each side has a job in each step. First, peer A sends a close frame and sends no further messages. Second, peer B answers with a close frame and sends no further messages. Third, peer A reads whatever peer B still had to send, then closes. Fourth, both sides drop the connection. The handshake exists so that no message is lost: a message sent just before the close still arrives, because the receiver keeps reading until the handshake finishes.

The subtlety is in how the reply is sent. When the underlying layer receives a close frame, it queues a close reply with the same code and reason, and that reply is written out the next time the socket is read from, written to, or flushed. The reply is queued, not sent, and it only leaves when the program touches the socket again. A handler that returns immediately never touches the socket again, so the reply sits in the queue while the socket is dropped, and the peer sees a reset. A handler that keeps calling recv drives the reply out, and the next recv returns the error or the end of the stream that says the handshake is done.

Why the Drain Loop Works

The drain loop is a second recv loop that runs after the close frame arrives, and it does nothing but wait for the socket to end:

while let Some(msg) = socket.recv().await {
    match msg {
        Ok(other) => println!("while draining: {other:?}"),
        Err(error) => {
            println!("drain ended: {error}");
            break;
        }
    }
}

Each recv in the drain drives the queued close reply toward the peer, and the loop ends when the socket reports that the handshake is complete, either with None or with an error such as ConnectionClosed. The loop prints any message that arrives during the drain, because the peer may still have sent data before its own close, and that data deserves to be seen rather than dropped. The loop is short in practice: the peer answers the reply at once, and the drain ends within a round trip.

Sending a Close From the Server

A server closes a connection by sending a close frame, and the shape is a send followed by a drain, because the server may still receive messages after sending its close:

src/main.rs
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() == "please close" {
            let frame = CloseFrame {
                code: 1000,
                reason: "bye".into(),
            };
            if socket.send(Message::Close(Some(frame))).await.is_err() {
                return;
            }
            println!("sent close frame");
            while let Some(msg) = socket.recv().await {
                match msg {
                    Ok(Message::Close(frame)) => {
                        println!("got close reply: {frame:?}");
                        break;
                    }
                    Ok(other) => println!("got after close: {other:?}"),
                    Err(error) => {
                        println!("recv error after close: {error}");
                        break;
                    }
                }
            }
            println!("handshake complete, returning");
            return;
        }
        if socket.send(Message::Text(text)).await.is_err() {
            return;
        }
    }
}

The client sends the text please close, and the server answers with a close frame carrying code 1000 and the reason bye, then drains until the client's close reply arrives. The live run of this exact code, from the verification project, shows both sides:

client asked server to close
client received: Close(Some(CloseFrame { code: Normal, reason: Utf8Bytes(b"bye") }))
client stream ended cleanly
close server sent close frame
close server got close reply: Some((1000, "bye"))
close server: handshake complete, returning

The client received the close frame, answered with its own, and the stream ended cleanly. The server received the reply and returned. The rule from the standard applies here too: after sending a close frame, the server may still read messages, but attempts to send another message will error, so the drain only reads.

Do Not Send After a Close:

After a close frame is sent or received, writing becomes impossible, and a further send returns an error. A handler that tries to send a reply after the close, or that sends a second close frame, gets an error for its trouble. The drain loop only reads, and the reading is what completes the handshake.

Variations

Closing without a frame

A bare close sends no code and no reason, and it is the simplest way to end a connection:

let _ = socket.send(Message::Close(None)).await;

The peer receives Message::Close(None) and knows the connection is ending, but not why. A bare close is fine for a client that is simply done, and a code with a reason is better for a server that wants to say why, such as shutting down or rejecting a message. The receiving side must handle None, as the two-arm match above shows.

Closing on shutdown

A server that is shutting down can close each connection with code 1001, going away, which tells clients the server is leaving on purpose rather than crashing:

let frame = CloseFrame {
    code: 1001,
    reason: "server shutting down".into(),
};
let _ = socket.send(Message::Close(Some(frame))).await;

The reason is human-readable, and a client that logs it can tell a planned shutdown from a failure. The send is followed by a drain, as in the server-initiated example, so the client's reply is received before the socket is dropped.

Dropping the socket for an unclean close

A connection can be ended at any time by dropping the WebSocket, which closes the TCP connection without a close frame. The peer sees an abnormal closure, code 1006, instead of a clean close. Dropping is appropriate when the peer has already misbehaved, for example by sending a frame that breaks the protocol, and there is no point in a polite goodbye. It is not appropriate for a normal ending, because the peer cannot tell a deliberate drop from a crash. The choice is between a clean close with a frame and an unclean close with a drop, and the normal path is the clean one.

Reading the close reason for logging

The reason is the most useful part of the frame for debugging, because it says why the other side left:

Message::Close(frame) => {
    match frame {
        Some(frame) => println!("closed: {} - {}", frame.code, frame.reason),
        None => println!("closed without a reason"),
    }
    return;
}

A server that logs every close with its code and reason builds a record of why clients leave, which is the first place to look when connections drop more often than expected. A log full of 1000s is a healthy server, and a log full of 1006s is a network problem.

A Plain Text Diagram of the Close Handshake

The handshake has two directions, and the drain is what makes the second one happen:

client sends Close(1000, "done")
        |
        v
server recv returns Message::Close
        |
        v
layer queues a Close reply (1000, "done")
        |
        v
server drains with recv until the socket ends
        |   (the drain flushes the queued reply)
        v
client receives Close(1000, "done")
        |
        v
both sides drop the connection

Without the drain step, the diagram stops at the queue, the reply never leaves, and the client sees a reset. The drain is the step that turns a queued reply into a sent one.

Testing It

The test below proves both directions of the handshake. It connects a client, sends a close frame, and asserts the client receives a close reply with the same code, then asks the server to close and asserts the client receives the server's frame. It needs tokio-tungstenite as a dev-dependency:

Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
tests/close_test.rs
use axum::{
    extract::ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};
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 };
        match msg {
            Message::Text(text) => {
                if text.as_str() == "please close" {
                    let frame = CloseFrame {
                        code: 1000,
                        reason: "bye".into(),
                    };
                    if socket.send(Message::Close(Some(frame))).await.is_err() {
                        return;
                    }
                    while let Some(msg) = socket.recv().await {
                        match msg {
                            Ok(Message::Close(_)) => break,
                            Ok(_) => continue,
                            Err(_) => break,
                        }
                    }
                    return;
                }
                if socket.send(Message::Text(text)).await.is_err() {
                    return;
                }
            }
            Message::Close(_) => {
                while let Some(msg) = socket.recv().await {
                    match msg {
                        Ok(_) => continue,
                        Err(_) => break,
                    }
                }
                return;
            }
            _ => {}
        }
    }
}

#[tokio::test]
async fn client_close_gets_reply_and_server_close_is_clean() {
    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.clone()).await.unwrap();
    assert_eq!(response.status(), 101);
    ws.send(ClientMessage::Close(Some(
        tokio_tungstenite::tungstenite::protocol::CloseFrame {
            code: tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode::Normal,
            reason: "done".into(),
        },
    )))
    .await
    .unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    assert!(matches!(msg, ClientMessage::Close(_)));
    let (mut ws, _) = connect_async(url.clone()).await.unwrap();
    ws.send(ClientMessage::Text("please close".into()))
        .await
        .unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    assert!(matches!(msg, ClientMessage::Close(_)));
    assert!(ws.next().await.is_none());
}

Run it with:

cargo test --test close_test
test client_close_gets_reply_and_server_close_is_clean ... ok

The first half asserts the drain: the client sends a close and receives one back. The second half asserts the server-initiated close: the client asks for it, receives the server's frame, and then the stream ends with None, which is the clean ending. The matches! checks only assert the kind, because the exact code and reason are covered by the live runs above.

Common Beginner Mistakes

Returning immediately on a close frame

// Wrong - the queued close reply is dropped with the socket
Message::Close(frame) => {
    println!("close: {frame:?}");
    return;
}

This is the mistake the live run at the top demonstrates. The handler returns, the socket is dropped, the queued reply never leaves, and the client sees "Connection reset without closing handshake". The fix is the drain loop, which keeps calling recv until the socket ends. The three extra lines are the difference between a clean close and a protocol error on the client.

Sending a close reply by hand

// Wrong - writing is impossible after a close frame is received
Message::Close(frame) => {
    let _ = socket.send(Message::Close(frame)).await;
    return;
}

The send fails, because writing becomes impossible the moment a close frame is received. The automatic reply is already queued by the layer underneath, and the handler's job is to drain, not to send. The fix is to delete the send and keep the drain. A manual close send is only correct when the server is the side initiating the close, before any close frame has been received.

Treating a bare close as an error

// Wrong - Close(None) is a normal close, not a failure
Message::Close(None) => {
    eprintln!("client closed without a reason, something is wrong");
    return;
}

A bare close is the most common close a client sends, and it means the client is done, not that something broke. The fix is to log it plainly and return, the same as a close with a frame. Reserve the error log for abnormal endings, where recv returns an error instead of a close message.

Closing with a made-up code

// Wrong - codes below 1000 and the reserved codes are not valid
let frame = CloseFrame {
    code: 999,
    reason: "done".into(),
};

Codes below 1000 are not valid close codes, and neither are 1004, 1005, and 1015, which are reserved. A peer that receives an invalid code may treat the close as a protocol error. The fix is to use 1000 for a normal close, 1001 for going away, or a code from 4000 upward for an application-specific reason. The table above lists the standard codes, and anything outside it needs a reason to exist.

Forgetting that a close ends the loop

// Wrong - continue after a close waits on a socket that will never speak again
Message::Close(_) => {
    println!("closed");
    continue;
}

continue goes back to recv, which returns None at once, because the stream ended with the close. The loop then ends anyway, so the continue is harmless but misleading: it suggests the connection is still alive when it is not. The fix is return, which says plainly that the connection is over. A close frame is the end of the conversation, and the code should read that way.

Final Complete Example

Here is everything from this page put together: the echo loop with the drain on a client close, the server-initiated close on request, and the test that proves both directions.

src/main.rs
use axum::{
    extract::ws::{CloseFrame, 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 };
        match msg {
            Message::Text(text) => {
                if text.as_str() == "please close" {
                    let frame = CloseFrame {
                        code: 1000,
                        reason: "bye".into(),
                    };
                    if socket.send(Message::Close(Some(frame))).await.is_err() {
                        return;
                    }
                    while let Some(msg) = socket.recv().await {
                        match msg {
                            Ok(Message::Close(_)) => break,
                            Ok(_) => continue,
                            Err(_) => break,
                        }
                    }
                    return;
                }
                if socket.send(Message::Text(text)).await.is_err() {
                    return;
                }
            }
            Message::Close(frame) => {
                println!("got close: {frame:?}");
                while let Some(msg) = socket.recv().await {
                    match msg {
                        Ok(other) => println!("while draining: {other:?}"),
                        Err(error) => {
                            println!("drain ended: {error}");
                            break;
                        }
                    }
                }
                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 close_test
cargo run

Summary

A close frame ends a connection on purpose, and the handshake around it has one step that is easy to miss: the close reply is queued when the frame arrives, and it only leaves when the handler keeps reading. The live runs proved the difference exactly, a return without a drain gave the client a reset, and a drain gave it a clean close reply with the same code and reason. The decision to carry forward is to treat every close as a two-part ending. The frame says the conversation is over, and the drain makes sure the goodbye actually arrives, and a server that does both gives its clients a clean ending every time. The next page puts the pieces together into the chapter's core example, the echo server, where every kind of message gets its answer.