Skip to content
systemcoding.dev
Concurrency

Write a TCP Echo Server in Rust with Tokio

Build a TCP echo server with Tokio's TcpListener, spawn one task per connection and copy bytes back, then test it with a client over loopback.

7 min read
Summarize in AI
Flat illustration of network packets crossing between two hosts, with the Rust, C and Wireshark logos.

An echo server is the "hello world" of network programming: it accepts a connection, reads bytes and writes the same bytes back. It is small enough to read in one sitting and it exercises the three things every Tokio server does, which are accepting connections, spawning a task per connection and moving bytes with async reads and writes. This post builds one with Tokio 1.x on Rust 1.90, tests it with a client in the same program, and then covers the two mistakes beginners meet first. If the words "task" and "future" are new, read the earlier post on what asynchronous I/O is before this one.

Project setup

Create a binary crate and add Tokio with the features this program uses:

Cargo.tomlTOML
[package]
name = "echo"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] }

The net feature provides TcpListener and TcpStream. The io-util feature provides the AsyncReadExt and AsyncWriteExt extension traits that add read and write_all. Without io-util the compiler reports that those methods do not exist, which confuses many first-time users.

The server

src/main.rsrust
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};

async fn handle(mut socket: TcpStream) {
    let mut buf = [0u8; 1024];
    loop {
        match socket.read(&mut buf).await {
            Ok(0) => return,                      // peer closed the connection
            Ok(n) => {
                if socket.write_all(&buf[..n]).await.is_err() {
                    return;                       // write failed, drop the connection
                }
            }
            Err(_) => return,
        }
    }
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:7878").await?;
    println!("listening on 127.0.0.1:7878");
    loop {
        let (socket, peer) = listener.accept().await?;
        println!("accepted {peer}");
        tokio::spawn(async move {
            handle(socket).await;
        });
    }
}

TcpListener::bind takes an address and returns a listener once the socket is bound and listening. accept().await resolves with a TcpStream and the peer's address each time a client connects. Between connections the task sleeps in Tokio's I/O driver and uses no CPU.

The important line is tokio::spawn. It moves the connection into its own task, so the accept loop goes straight back to waiting for the next client. If you called handle(socket).await directly in the loop instead, the server would serve one client at a time, because the loop would be stuck inside the first client's handle until it disconnected.

Reading and writing

socket.read(&mut buf) fills as much of the buffer as is available and returns the byte count. It returns Ok(0) only when the peer has closed its sending side, which is the signal to stop. It may return fewer bytes than were sent in one message, because TCP is a byte stream with no message boundaries. For an echo server that does not matter: whatever arrives is sent straight back.

write_all loops until every byte is written. Plain write may write only part of the buffer and return how many bytes it accepted, so using it without a loop is a classic bug that appears only under load. For a server that frames messages, such as one that reads lines, read the Tokio documentation for BufReader and AsyncBufReadExt::read_line.

A client to test it

Run the server in one terminal. To test it without extra tools, here is a small client in a second binary file, src/bin/client.rs, that sends a message and prints the reply:

src/bin/client.rsrust
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:7878").await?;
    stream.write_all(b"hello tokio").await?;
    let mut buf = [0u8; 11];
    stream.read_exact(&mut buf).await?;
    println!("echoed: {}", String::from_utf8_lossy(&buf));
    Ok(())
}

Start the server with cargo run --bin echo, then in another terminal run cargo run --bin client.

Text
listening on 127.0.0.1:7878
accepted 127.0.0.1:52144
Text
echoed: hello tokio

The first block is the server's output. The port number after accepted is chosen by the operating system for each client and will differ on your machine. The second block is the client's. The client uses read_exact because it knows how many bytes to expect: eleven, the length of hello tokio. A single read could legally return fewer.

You can also test with nc 127.0.0.1 7878 from a shell: every line you type is echoed back.

What happens when a client disconnects

When the client program exits, its side of the connection closes. The server's pending read returns Ok(0), handle returns, the TcpStream is dropped and the socket is closed. The task ends and Tokio frees it. Nothing else is needed for cleanup, because Rust drops the stream at the end of handle.

If the client vanishes without closing cleanly, for example when a cable is pulled, the server may wait a long time in read, since TCP does not announce a lost peer until a timeout. Production servers add an idle timeout with tokio::time::timeout around the read.

Two mistakes that bite first

The first mistake is blocking the runtime. Do not call std::net::TcpListener::accept or std::thread::sleep inside these tasks. Those block the worker thread, and with the default runtime that has one thread per CPU core, a handful of blocked tasks can freeze a whole server. Use the tokio::net and tokio::time equivalents.

The second mistake is spawning inside a closure that borrows. The async move block passed to tokio::spawn must own everything it uses, because the task may outlive the loop iteration that created it. Compiler messages mentioning 'static almost always mean a borrow crossed a spawn. Moving the socket into the block fixes it here.

Letting the kernel do the copying

The server above copies bytes through a user-space buffer. For a pure echo, Tokio offers tokio::io::copy, which does the read and write loop for you and handles partial writes:

src/main.rsrust
use tokio::net::{TcpListener, TcpStream};

async fn handle(socket: TcpStream) {
    let (mut reader, mut writer) = socket.into_split();
    let _ = tokio::io::copy(&mut reader, &mut writer).await;
}

into_split divides the stream into independent read and write halves, which lets you pass each to a function that wants ownership. copy returns the number of bytes moved, and when the peer closes it returns normally. This version is shorter and has fewer places to go wrong, so prefer it once you understand the loop version.

Limiting connections and handling errors

An accept loop that spawns without limit lets one misbehaving client population exhaust file descriptors. Accepting itself can fail with errors such as "too many open files" when the process hits its descriptor limit, and the loop above would then return from main through the ?. A server that must stay up treats accept errors as recoverable: log the error, sleep briefly, and continue the loop. Tokio's own tutorial on I/O uses a Semaphore to cap concurrent connections, acquiring a permit before spawning and releasing it when the task ends. That keeps memory bounded, since each connection holds a buffer and a task.

Per-connection errors should stay per-connection. In handle, a failed read or write ends only that task. The server loop does not see it, which is the isolation you want. If you need to know why a connection ended, return a Result from handle, and log it inside the spawned block instead of ignoring it.

Choosing the buffer size

The 1024-byte buffer is a teaching value. Each read call can return at most that many bytes, so a client that sends 1 MiB costs about a thousand read and write round trips through the runtime. A buffer of 4 KiB to 64 KiB cuts the number of trips, at the price of memory per connection, and it lives on the task's stack frame inside the future, so it also grows the size of every spawned task. For an echo server the numbers are not critical. For a real protocol, size the buffer to your typical message and reuse it across reads rather than allocating one per message.

Seeing concurrency at work

To convince yourself the server is concurrent, open two nc sessions at once. Type into the first, then the second, then the first again. Each echoes immediately, in whatever order you type, because the two connections are separate tasks. If you replace tokio::spawn with a direct .await of handle, the second nc connects, since the kernel completes the TCP handshake and queues it in the listen backlog, but nothing is echoed until the first one closes. That experiment shows exactly what the spawn is buying you.

Also inNetworking
Share

Keep reading

Flat illustration of a microcontroller wired to an LED and a sensor, with the Bluetooth, Nordic Semiconductor and Arm logos.
Embedded

Create a Custom BLE GATT Service on nRF52

Define a custom 128-bit GATT service on nRF52 with Zephyr: characteristic properties, read and write callbacks, notifications through the CCC and MTU limits.

9 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.