Sub topic 16
Putting it together: a concurrent TCP echo server
This chapter combines the runtime, tasks, async I/O and timers from earlier chapters into one small service. It assumes you can read basic async fn code, know what tokio::spawn does, and understand why a spawned task must be Send + 'static. Everything else is built up from there.
What the server does
An echo server accepts TCP connections and writes back every byte it receives. The protocol is trivial, but the structure is the same as in a chat server, a proxy or an HTTP server:
- One loop accepts connections.
- Each connection gets its own task.
- Each task reads and writes until the peer leaves or an error occurs.
Because each connection is a task and not a thread, thousands of idle clients cost a few kilobytes each. The runtime's worker threads only run a task when its socket is ready.
Project setup
Create the project and add Tokio. The full feature set is the simplest choice while learning.
[package]
name = "echo"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }The code below needs these features: macros and rt-multi-thread for #[tokio::main], net for TcpListener, io-util for the read and write helpers, and time for timeouts. If you trim full later, enable at least those.
The baseline server
This version is the smallest correct echo 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,
}
}
});
}
}Several details matter here.
bind(...).await?is async because name resolution may be involved. A bind failure, such as the port already being in use, endsmainwith an error, which is what you want at startup.accept().awaitsuspends the main task until a client connects. While it waits, the worker thread runs other tasks.async movemovessocketinto the new task. The task owns the socket, which satisfies the'staticbound.TcpStreamisSend, so the multi-thread runtime can move the task between workers.readreturnsOk(0)when the peer closes its sending side. That is the normal end of a connection, not an error.write_allloops until every byte is written. Plainwritemay write only part of the buffer.
How a connection flows
The diagram shows the interaction between the accept loop, a connection task and a client.
The accept loop never touches client data. If it did, one slow client would delay every new connection.
Trying it out
Start the server with cargo run, then connect from two terminals. Anything you type comes back.
nc 127.0.0.1 8080You can also write a Rust client with the same runtime. This one sends a message and reads the same number of bytes back.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
let msg = b"hello tokio";
stream.write_all(msg).await?;
let mut reply = vec![0u8; msg.len()];
stream.read_exact(&mut reply).await?;
println!("{}", String::from_utf8_lossy(&reply));
Ok(())
}read_exact keeps reading until the buffer is full. A single read call may return fewer bytes than were sent, because TCP is a byte stream and does not preserve message boundaries.
Hardening the server
The baseline works but fails quietly in three ways. Each fix uses a tool from an earlier chapter.
Move the logic into a function
A separate async fn that returns io::Result lets you use ? and report errors in one place.
Add an idle timeout
A client that connects and never sends anything holds a task and a file descriptor forever. Wrapping each read in tokio::time::timeout closes idle connections. timeout returns Err(Elapsed) if the inner future does not finish in time, and it drops that future.
Survive accept errors
accept can fail for reasons unrelated to the server's health, for example when the process runs out of file descriptors. Using ? there would shut down the whole server. Log the error, wait briefly and continue.
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::time::{sleep, timeout};
const IDLE_TIMEOUT: Duration = Duration::from_secs(30);
async fn handle(mut socket: TcpStream) -> std::io::Result<()> {
let mut buf = [0u8; 1024];
loop {
let n = match timeout(IDLE_TIMEOUT, socket.read(&mut buf)).await {
Ok(result) => result?,
Err(_elapsed) => return Ok(()),
};
if n == 0 {
return Ok(());
}
socket.write_all(&buf[..n]).await?;
}
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (socket, addr) = match listener.accept().await {
Ok(pair) => pair,
Err(e) => {
eprintln!("accept failed: {e}");
sleep(Duration::from_millis(100)).await;
continue;
}
};
tokio::spawn(async move {
if let Err(e) = handle(socket).await {
eprintln!("connection {addr} failed: {e}");
}
});
}
}The timeout wraps only the read, not the write. If the peer stops reading, write_all can also wait indefinitely once the kernel's send buffer fills. A production server would put a timeout around the write as well.
Cancellation in this server
timeout works by dropping the read future when time runs out. That is safe here because TcpStream::read is cancel safe: if it is dropped before completing, no data has been consumed. write_all is not cancel safe. If you dropped it midway, some bytes would be sent and you could not tell how many. That is why the code never wraps the write in a select! branch that might abandon it halfway.
Using the library copy helper
Echoing is a copy from the read half to the write half of the same socket. Tokio provides tokio::io::copy for this, and it uses an internal buffer and handles partial writes.
use tokio::io;
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> 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 reader, mut writer) = socket.split();
if let Err(e) = io::copy(&mut reader, &mut writer).await {
eprintln!("copy failed: {e}");
}
});
}
}split borrows the socket and gives two halves that can be used at the same time. The borrow is fine because the socket lives inside the same task. If you needed the halves in different tasks, use into_split, which returns owned halves.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Using `std::net::TcpListener` | `accept` blocks a worker thread | Use `tokio::net::TcpListener` |
| Handling a client inside the accept loop | One client stalls all new connections | `tokio::spawn` per connection |
| Treating `read` as returning whole messages | Truncated or merged data | Use `read_exact` or add framing |
| Ignoring the `Ok(0)` case | Busy loop on a closed socket | Return when `read` yields 0 |
| Using `?` on `accept` in the loop | A temporary error stops the server | Log and continue |
| Spawned tasks that are never awaited | Panics are only visible in the `JoinHandle` | Log inside the task or keep the handles |
A panic inside a connection task does not take down the server. Tokio catches it and reports it through the task's JoinHandle. Since this server drops the handles, the panic message is printed by the default panic hook and the connection is closed.
What is still missing
This server runs until you press Ctrl+C, which kills every connection abruptly. It also has no limit on concurrent connections. Graceful shutdown and connection limits build on the same structure, with a signal future raced against accept in a select! and a way to wait for the connection tasks to finish.
Exercise
In the hardened server, why is the idle timeout applied around socket.read and not around the whole handle function?
Show answer
A timeout around the whole function would cut off every connection after 30 seconds, even if the client was actively sending data. Wrapping only the read measures idle time between messages, and the timer restarts on every loop iteration.
Exercise
The accept loop calls tokio::spawn(async move { ... handle(socket) ... }). What would go wrong if you wrote handle(socket).await directly in the loop body instead?
Show answer
The accept loop would serve one client at a time. Until the current client disconnected, no other connection would be accepted, so the server would not be concurrent.
Exercise
Why does the echo client use read_exact instead of a single read call?
Show answer
TCP delivers a byte stream, so one read can return fewer bytes than the server sent. read_exact keeps reading until the buffer is full, so the client gets the whole reply.