Splitting sender and receiver
Learn how to split a WebSocket into a sender half and a receiver half so a server can read and write at the same time
A WebSocket can send and receive at the same time, but one piece of code cannot do both through a single handle. The send method and the recv method both need exclusive access to the socket, so a task that is waiting for the next incoming message cannot send anything until that wait ends, and a task that is sending cannot notice a new message arriving. The fix is to split the socket into two halves: a sender that only sends, and a receiver that only receives. Each half is owned by a different task, and both tasks run at once.
Where This Fits
The previous page showed that a WebSocket connection stays open and either side can speak at any time. This page is about the server side of that freedom: how one connection can carry traffic in both directions simultaneously. Think of a walkie-talkie with one button. One person talks while the other listens, and they take turns. Splitting turns it into a telephone, where both people can talk and listen at the same time because each direction has its own channel.
The Smallest Working Version First
Here is a complete server that splits every connection. The sender half pushes a tick to the client every half second. The receiver half reads whatever the client sends. Both run at once.
# Cargo.toml
[package]
name = "ws-learn"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8.9", features = ["ws"] }
tokio = { version = "1.54.1", features = ["full"] }
futures-util = "0.3"
// src/main.rs
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use std::time::Duration;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(socket: WebSocket) {
let (mut sender, mut receiver) = socket.split();
let send_task = tokio::spawn(async move {
let mut n = 0u32;
loop {
n += 1;
let text = format!("tick {n} from server");
if sender.send(Message::text(text)).await.is_err() {
break;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
});
while let Some(msg) = receiver.next().await {
match msg {
Ok(Message::Text(text)) => {
println!("server received text: {text}");
}
Ok(Message::Close(_)) => break,
Ok(_) => {}
Err(_) => break,
}
}
send_task.abort();
println!("server: receiver ended, sender aborted");
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", any(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it with cargo run. Then connect with a client that sends a message while also reading. The client below splits its own side too, so its read task and its send call run at the same time.
// src/bin/ws_client.rs
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message};
#[tokio::main]
async fn main() {
let (ws, _) = connect_async("ws://127.0.0.1:3000/ws").await.unwrap();
let (mut write, mut read) = ws.split();
let read_task = tokio::spawn(async move {
let mut seen = 0;
while let Some(msg) = read.next().await {
match msg {
Ok(Message::Text(t)) => {
println!("client received: {t}");
seen += 1;
if seen >= 3 {
break;
}
}
Ok(other) => println!("client received other: {other:?}"),
Err(e) => {
println!("client read error: {e}");
break;
}
}
}
});
write
.send(Message::Text("hello from client".into()))
.await
.unwrap();
println!("client sent: hello from client");
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
read_task.abort();
println!("client done: sent and received at the same time");
}
This client needs tokio-tungstenite = "0.28" in Cargo.toml. Run it with cargo run --bin ws_client while the server is running. The live run printed:
client sent: hello from client
client received: tick 1 from server
client received: tick 2 from server
client received: tick 3 from server
client done: sent and received at the same time
And the server printed:
server received text: hello from client
server: receiver ended, sender aborted
Read those two outputs together. The client sent its message while ticks were already arriving. The server received the message while its sender task was still ticking. Neither direction waited for the other. That simultaneity is what splitting buys.
Both Directions at Once:
If the client prints its sent line before the first tick and still receives three ticks, both directions ran concurrently. If the ticks only started after the client finished sending, the two directions were taking turns, and the split is not doing its job.
Why One Handle Cannot Do Both
The reason splitting exists is a rule in Rust, not a rule in WebSocket. A WebSocket value has two methods that matter here: send, which takes &mut self, and recv, which also takes &mut self. The &mut means exclusive access: while one piece of code holds the mutable borrow, no other code can borrow the socket at all.
A single task that loops on recv().await holds that borrow across the wait. While it waits for the next message, it cannot call send, because the borrow is still held. A task that wants to send a tick every half second would have to wait for a message to arrive first, which defeats the purpose of the tick. The two directions block each other through the shared handle.
Splitting breaks that sharing. socket.split() consumes the socket and returns two values that each own one direction. The sender owns the write side. The receiver owns the read side. Neither borrows the other, so each can be moved into its own task. The Rust compiler is satisfied because there is no shared borrow any more, and the program is correct because the underlying connection really does have two independent directions.
The split comes from StreamExt::split, a method on the futures-util crate. WebSocket implements the Stream trait for receiving and the Sink trait for sending, and split is the standard way to separate a value that is both a stream and a sink. The two halves have their own types, and those types are worth naming because they appear in every split example: the sender is a SplitSink<WebSocket, Message>, and the receiver is a SplitStream<WebSocket>.
Reading the Split Code Line by Line
The socket function is short, and its shape is the pattern for the rest of the chapter, so each line earns a close look.
let (mut sender, mut receiver) = socket.split();
socket.split() consumes the WebSocket and returns a pair. The let (mut sender, mut receiver) pattern takes the pair apart into two variables. Both are mut because sending and receiving both need mutable access to their own half. After this line the name socket no longer exists: it was moved into the split, and only the two halves remain.
let send_task = tokio::spawn(async move {
tokio::spawn starts a new task, a lightweight unit of work that Tokio runs alongside the current task. The async move block is the code the new task runs, and move means the block takes ownership of the values it uses, which here is sender. The return value is a JoinHandle, stored as send_task, which is the handle the main task uses later to stop the sender.
if sender.send(Message::text(text)).await.is_err() {
break;
}
sender.send needs the SinkExt trait, which is why the imports include futures_util::sink::SinkExt. Sending returns a Result. If it fails, the client is gone, and the task breaks out of its loop. A send that keeps retrying after the client left would spin forever, so the error check is the exit condition for the sender task.
while let Some(msg) = receiver.next().await {
receiver.next() needs the StreamExt trait, which is why the imports include futures_util::stream::StreamExt. Each call waits for the next incoming message. It returns Some while messages arrive and None when the connection ends. The while let loop runs until the connection ends, which is the normal exit for the receiver.
send_task.abort();
When the receiver loop ends, the client is gone, and the sender task has nothing left to send to. abort stops the spawned task. Without this line the sender task would keep trying to send ticks to a dead connection until its next send failed, which would happen at once in practice, but aborting is immediate and explicit. It also prevents the task from lingering if the send is slow to fail.
The Concept Behind the Split
A WebSocket connection is really two one-way channels sharing one wire. Messages from the client travel in one direction. Messages from the server travel in the other. Nothing in the protocol ties a reply to a request, and nothing forces the two directions to take turns.
The unsplit socket hides that independence behind a single handle, which is convenient for an echo server: receive one message, send it straight back, repeat. The moment the server wants to send something that is not a reply, such as a tick, a notification, or a broadcast, the single handle becomes a bottleneck. The split restores the independence the protocol already has. Each direction gets its own owner, its own task, and its own rhythm.
A useful mental model is a two-lane road. The unsplit socket is a single lane with a traffic light: traffic flows one way, then the other, and someone has to manage the turns. The split socket is two lanes: traffic flows both ways continuously, and neither lane waits for the other.
Why This Design
Splitting by moving halves into tasks has three properties that matter in real servers.
First, each direction can block without affecting the other. The receiver can wait indefinitely for the next message. The sender can sleep between ticks. Neither wait touches the other direction, because they are separate tasks with separate halves.
Second, the compiler enforces the separation. A sender half cannot receive, and a receiver half cannot send, because the types do not offer those methods. A mistake such as trying to read from the sender half is a compile error, not a runtime surprise. The type system carries the design.
Third, shutdown becomes explicit. The receiver ending is the signal that the client is gone. The code that owns the receiver is the code that decides the connection is over, and it is the code that stops the sender. There is one place where the connection ends, and it is visible in the function.
A Richer Example With a Channel Between the Tasks
The smallest example has a weakness: the receiver task cannot send anything back. It can only print what arrives. A real handler usually needs to reply to what it receives, and the reply has to travel through the sender half, which lives in another task. The standard answer is a channel: a pipe that carries messages from the receiver task to the sender task.
Tokio provides mpsc, a multi-producer single-consumer channel. The receiver task holds the sending end. The sender task holds the receiving end. The receiver task forwards every client message into the channel, and the sender task sends whatever comes out of the channel to the client, along with its ticks.
// src/main.rs
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use std::time::Duration;
use tokio::sync::mpsc;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(socket: WebSocket) {
let (mut sender, mut receiver) = socket.split();
let (tx, mut rx) = mpsc::channel::<Message>(32);
let send_task = tokio::spawn(async move {
let mut ticker = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::select! {
_ = ticker.tick() => {
let text = "tick from server";
if sender.send(Message::text(text)).await.is_err() {
break;
}
}
msg = rx.recv() => {
match msg {
Some(message) => {
if sender.send(message).await.is_err() {
break;
}
}
None => break,
}
}
}
}
});
while let Some(msg) = receiver.next().await {
match msg {
Ok(Message::Text(text)) => {
let reply = format!("echo: {text}");
if tx.send(Message::text(reply)).await.is_err() {
break;
}
}
Ok(Message::Close(_)) => break,
Ok(_) => {}
Err(_) => break,
}
}
drop(tx);
send_task.abort();
println!("server: receiver ended, sender aborted");
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", any(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The channel is created with capacity 32, which means up to 32 messages can wait in the pipe before the sender of the channel has to wait. If the receiver task produces replies faster than the sender task can write them, the channel fills up and tx.send().await pauses the receiver task until there is room. That pause is backpressure: the system slows the fast side down instead of letting messages pile up without limit.
The sender task now watches two things at once with tokio::select!, a macro that waits for whichever branch is ready first. The timer branch sends a tick every second. The channel branch sends whatever the receiver task forwarded. Either branch can fail on send, and either failure ends the task, because a failed send means the client is gone.
The receiver task forwards each text message as an echo through the channel instead of sending it directly. It cannot send directly, because it does not own the sender half. That constraint is the whole point of the design: all writes go through one task, so writes never race each other.
After the receiver loop ends, the code drops tx, the sending end of the channel. Dropping it closes the channel, so the sender task's rx.recv() returns None and the sender task would end on its own. The code still calls send_task.abort() right after, which ends the task at once instead of waiting for the channel to drain. Both lines are belt and braces: the drop is the clean signal, and the abort is the immediate stop.
All Writes Must Go Through One Task:
Once a socket is split, only the task that owns the sender half may write. If any other task also tries to write, it cannot, because it does not own the half. That is a feature, not a limitation: it means writes can never interleave halfway through a message. Route every outgoing message through the sender task, usually through a channel as shown here.
Two Variations Worth Knowing
One task with select instead of two tasks
Splitting into two tasks is not the only way to do both directions at once. A single task can watch the receiver and a timer together with tokio::select!, which is what the richer example already does inside the sender task. A fully single-task version looks like this:
// Inside handle_socket, after splitting
let (mut sender, mut receiver) = socket.split();
let mut ticker = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::select! {
_ = ticker.tick() => {
if sender.send(Message::text("tick")).await.is_err() {
break;
}
}
msg = receiver.next() => {
match msg {
Some(Ok(Message::Text(text))) => {
println!("received: {text}");
}
Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
Some(Ok(_)) => {}
}
}
}
}
This version has no spawned task and no channel. It fits when the only things the server sends are timer ticks and replies that can be sent directly from the receive branch. It stops fitting the moment something outside the socket task needs to send, such as another connection or a background job, because that something cannot reach into this loop. The two-task version with a channel fits that case, because the channel sender can be shared with anyone.
Sharing the sender across tasks
The channel sender, tx, is cheap to clone. Each clone is another producer that can push messages into the same pipe. That is how a handler that serves many clients gives each connection its messages: the shared state holds one tx per connection, and any task that wants to send to a particular client clones that connection's tx and sends into it. The sender task for that connection is the only task that ever writes to its socket. This shape is the bridge between splitting and the connection tracking on the next pages: one sender task per connection, fed by a channel, with the channel sender stored where other code can find it.
The Split as a Diagram
The diagram shows where each half lives and what flows through it.
Client Server
| |
| frames in either direction |
| <--------------------------> |
| | socket.split()
| | |
| | +--> sender half (SplitSink)
| | | owned by send task
| | | sends ticks, replies
| | |
| | +--> receiver half (SplitStream)
| | owned by handle task
| | reads client messages
| | forwards replies via channel
| |
| | receiver ends -> abort sender task
The two halves never touch each other after the split. The only link between the tasks is the channel, and the channel carries messages, not shared access to the socket.
Testing the Split
A test for the split needs to prove the property that makes splitting worth doing: a message the client sends is received by the server while the server is also sending on its own schedule. The test below runs a server that ticks every 100 milliseconds and echoes what it receives through a channel, then connects a client that sends one message and checks it gets both the echo and a tick back.
# Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.28"
futures-util = "0.3"
// tests/split_test.rs
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_tungstenite::connect_async;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(socket: WebSocket) {
let (mut sender, mut receiver) = socket.split();
let (tx, mut rx) = mpsc::channel::<Message>(32);
let send_task = tokio::spawn(async move {
let mut ticker = tokio::time::interval(Duration::from_millis(100));
loop {
tokio::select! {
_ = ticker.tick() => {
if sender.send(Message::text("tick")).await.is_err() {
break;
}
}
msg = rx.recv() => {
match msg {
Some(message) => {
if sender.send(message).await.is_err() {
break;
}
}
None => break,
}
}
}
}
});
while let Some(msg) = receiver.next().await {
match msg {
Ok(Message::Text(text)) => {
let _ = tx.send(Message::text(format!("echo: {text}"))).await;
}
Ok(Message::Close(_)) => break,
Ok(_) => {}
Err(_) => break,
}
}
drop(tx);
send_task.abort();
}
#[tokio::test]
async fn split_carries_both_directions_at_once() {
let app = Router::new().route("/ws", any(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 (ws, _) = connect_async(&url).await.unwrap();
let (mut write, mut read) = ws.split();
write
.send(tokio_tungstenite::tungstenite::Message::Text(
"hello".into(),
))
.await
.unwrap();
let mut saw_echo = false;
let mut saw_tick = false;
for _ in 0..10 {
let msg = read.next().await.unwrap().unwrap();
if let tokio_tungstenite::tungstenite::Message::Text(text) = msg {
if text.as_str() == "echo: hello" {
saw_echo = true;
}
if text.as_str() == "tick" {
saw_tick = true;
}
}
if saw_echo && saw_tick {
break;
}
}
assert!(saw_echo, "client should receive the echo of its message");
assert!(saw_tick, "client should receive a server tick");
}
The test reads up to ten messages and watches for two specific ones: the echo of its own message and a server tick. The order does not matter, and that is deliberate. The echo and the tick come from different tasks, so either one can arrive first. A test that demanded the echo before the tick would be testing an ordering the design does not promise. The two assertions together prove both directions work while the connection is open.
Common Beginner Mistakes
Forgetting the SinkExt and StreamExt imports
// Wrong - send and next are trait methods, not inherent methods
let (mut sender, mut receiver) = socket.split();
sender.send(Message::text("hi")).await;
receiver.next().await;
send comes from futures_util::sink::SinkExt, and next comes from futures_util::stream::StreamExt. Without those imports the compiler reports that no method named send or next exists, even though the split itself compiled. The fix is the two imports at the top of the file. This is the most common compile error on this page, and it looks confusing because the error points at the method call rather than at the missing import.
Using the socket after splitting it
// Wrong - socket was consumed by split
let (mut sender, mut receiver) = socket.split();
socket.send(Message::text("hi")).await;
split consumes the socket. After the call, the name socket is gone. Any code that still mentions it fails to compile with a "use of moved value" error. The fix is to use sender for every write and receiver for every read.
Spawning the sender and forgetting to stop it
// Wrong - the sender task keeps running after the client leaves
let _send_task = tokio::spawn(async move {
loop {
sender.send(Message::text("tick")).await.unwrap();
}
});
A spawned task that never ends is a leak: it holds memory and keeps trying to write to a dead connection. The unwrap on send makes it worse, because the first failed send panics the task instead of ending it cleanly. Always keep the JoinHandle, check send errors with is_err and break, and abort the task when the receiver ends.
Sending from the receiver task directly
// Wrong - the receiver task does not own the sender half
while let Some(msg) = receiver.next().await {
if let Ok(Message::Text(text)) = msg {
sender.send(Message::text(text)).await.unwrap();
}
}
This code fails to compile if sender was moved into another task, and it defeats the split if it was not. The receiver task must forward replies through a channel to the sender task. If the reply is sent directly from the receiver branch, there was no reason to split in the first place, and the timer branch would have nowhere to live.
A Split Socket Has No Single Owner Any More:
After split, there is no one value that represents the connection. The connection ends when the receiver ends, and the code that owns the receiver is responsible for stopping the sender. If that code forgets, the sender task outlives the connection. Keep the JoinHandle and abort it on the same path where the receiver loop ends.
Final Complete Example
Here is everything from this page in one place: the server that splits every connection, ticks from the sender task, echoes through a channel from the receiver task, and stops the sender task when the client leaves.
// src/main.rs
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use std::time::Duration;
use tokio::sync::mpsc;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(socket: WebSocket) {
let (mut sender, mut receiver) = socket.split();
let (tx, mut rx) = mpsc::channel::<Message>(32);
let send_task = tokio::spawn(async move {
let mut ticker = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::select! {
_ = ticker.tick() => {
if sender.send(Message::text("tick from server")).await.is_err() {
break;
}
}
msg = rx.recv() => {
match msg {
Some(message) => {
if sender.send(message).await.is_err() {
break;
}
}
None => break,
}
}
}
}
});
while let Some(msg) = receiver.next().await {
match msg {
Ok(Message::Text(text)) => {
let reply = format!("echo: {text}");
if tx.send(Message::text(reply)).await.is_err() {
break;
}
}
Ok(Message::Close(_)) => break,
Ok(_) => {}
Err(_) => break,
}
}
drop(tx);
send_task.abort();
println!("server: receiver ended, sender aborted");
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", any(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the server and the client from the first section. The client receives ticks and its own echo, and the server prints the message it received and the cleanup line when the client leaves. Every line of output is one half of the split doing its job.
Summary
Splitting is the answer to a borrowing problem with a protocol truth behind it. One handle cannot send and receive at once because both methods need exclusive access, and a task waiting on one direction cannot serve the other. split turns the single handle into two owned halves, each with its own type, each movable into its own task. The sender task writes. The receiver task reads. A channel connects them when a reply has to travel from the reader to the writer.
The decision that follows from this page is about where writes live. If only the socket task ever sends, one task with a select loop is enough. If anything outside the socket task must send, that something needs a channel sender, and the socket needs its own sender task to drain the channel. Either way, the connection ends in one place: the receiver loop. The next page is about what happens in that place, and what the server must clean up when the loop ends because the client is gone.