Sub topic 16
Putting it together: a concurrent TCP echo server
This chapter assumes you know #[tokio::main], tokio::spawn, and the Send and 'static bounds on spawned tasks. It combines async I/O and tasks into one working server.
The design
An echo server sends back every byte it receives. The design has two levels:
- One loop accepts connections.
- Each accepted connection gets its own task that reads and writes until the client leaves.
Because each connection lives in its own task, a slow client never blocks the others. The accept loop only waits for new sockets, so it stays responsive.
The server
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0u8; 1024];
loop {
match socket.read(&mut buf).await {
Ok(0) => return,
Ok(n) => {
if socket.write_all(&buf[..n]).await.is_err() {
return;
}
}
Err(_) => return,
}
}
});
}
}How it works
TcpListener::bindreserves the address.accept().awaitsuspends until a client connects, and it yields aTcpStreamplus the peer address.async movetransfers ownership ofsocketinto the task. This satisfies the'staticbound, because the task borrows nothing frommain.readreturns the number of bytes placed inbuf. A result ofOk(0)means the peer closed its side, so the task returns and drops the socket.write_allkeeps writing until the whole slice is sent. Plainwritemay send only part of it.- Any I/O error ends only that connection's task. The accept loop is unaffected.
The buffer lives inside the task, so each connection has its own 1 KiB. The TcpStream is Send, so the task can move between worker threads.
Try it
Run the server with cargo run. Open two terminals and connect with nc 127.0.0.1 8080. Type a line in each one. Each client gets its own text back, and a pause in one terminal does not delay the other.
Common mistakes
- Using
writeinstead ofwrite_all. Data can be silently truncated. - Ignoring
Ok(0). The loop spins forever on a closed socket. - Calling blocking code in the task.
std::thread::sleepor a blocking read stalls a worker thread. Usespawn_blockingfor that work. - No shutdown path. This server runs until the process is killed. Graceful shutdown combines
select!with a signal or a cancellation channel.
Exercise
The server never calls .join or awaits the JoinHandle returned by tokio::spawn. Why is that acceptable here, and what do you lose by discarding the handle?
Show answer
Dropping a JoinHandle detaches the task, and it keeps running. That suits a per-connection task whose result nobody needs. You lose the ability to read the task's return value or to find out that it panicked, and you cannot wait for all connections to finish during shutdown. A panic in one task is contained to that task and does not stop the accept loop.
Exercise
What changes if you remove async move and write a plain async block that uses socket?
Show answer
The code no longer compiles. The block would borrow socket from the loop iteration, so the future is not 'static, and tokio::spawn requires 'static. The move keyword gives the task ownership of the socket.