A chat server in 90 lines of Tokio

TermChat's server: one broadcast channel, one task per connection, and select! to read and write at once. Then the four bugs I'd fix before anyone else ran it.

On this page
  1. The design
  2. Accepting connections
  3. Framing
  4. The connection loop
  5. The client
  6. Four bugs to fix before anyone else runs it
  7. Takeaways

The design

TermChat is group chat in the terminal: one server, many clients, plain TCP, one room. I wrote it to learn async Rust properly. The server came out small enough to read in one sitting, which makes it a good map of how Tokio fits together.

Three pieces:

  1. A TcpListener accepting connections in a loop.
  2. One tokio::sync::broadcast channel. Every message from any client goes in; every client reads everything out.
  3. One task per connection, doing two things at once: socket lines into the channel, channel lines out to the socket.

Accepting connections

let listener = TcpListener::bind("0.0.0.0:8080").await?;
let (tx, _) = broadcast::channel::<String>(1024);
let active_users = Arc::new(Mutex::new(HashSet::new()));

loop {
    let (socket, addr) = match listener.accept().await {
        Ok(res) => res,
        Err(e) => { error!("Failed to accept connection: {}", e); continue; }
    };
    let tx = tx.clone();
    let mut rx = tx.subscribe();
    let active_users = active_users.clone();
    tokio::spawn(async move { /* one connection */ });
}

broadcast::channel(1024) returns a sender and a receiver. The sender clones freely, and subscribe() makes a new receiver that sees every message sent after it was created. Each connection gets a sender to publish with and its own receiver to listen on.

The user list is a HashSet behind Tokio's async Mutex, shared with Arc. The lock is held for a few lines, so a std mutex would do. The async one is harmless.

Framing

TCP is a byte stream, so the protocol needs message boundaries. tokio-util's Framed with LinesCodec turns the socket into a Stream of String lines and a Sink to send lines into:

let mut framed = Framed::new(socket, LinesCodec::new());

The first line a client sends is its username. After that the server sends three shapes:

USERS|alice,bob,carol
MSG|alice|hey, anyone here?
MSG|SYSTEM|carol joined the chat

The connection loop

After registering the name and announcing the join, each task runs:

loop {
    tokio::select! {
        result = framed.next() => match result {
            Some(Ok(msg)) => { let _ = tx.send(format!("MSG|{}|{}", username, msg)); }
            Some(Err(e)) => warn!("Codec error from {}: {}", username, e),
            None => break,
        },
        Ok(msg) = rx.recv() => {
            if let Err(e) = framed.send(msg).await {
                warn!("Failed to write to {}: {}", username, e);
                break;
            }
        }
    }
}

select! waits on both futures and runs whichever branch finishes first. A line from the client goes into the channel. A message from the channel goes to the client. When the socket closes, framed.next() returns None and the loop ends; the task then removes the user, broadcasts the new user list and a leave message, and drops everything.

That is the whole server. No locks around sockets, no thread management.

The client

A Ratatui app with three panes: history, users, input. Networking runs in a spawned task that forwards incoming lines over an mpsc channel. The draw loop polls the keyboard with a 16 ms timeout (about 60 frames a second) and drains the channel with try_recv() between frames, so the UI never blocks on the network.

One detail worth copying: a panic hook installed before raw mode, so a crash restores the terminal instead of leaving a broken shell.

std::panic::set_hook(Box::new(|info| {
    let _ = disable_raw_mode();
    let _ = std::io::stdout().execute(LeaveAlternateScreen);
    eprintln!("Panic: {:?}", info);
}));

Four bugs to fix before anyone else runs it

The README says TermChat is cleartext and unauthenticated. These matter even on a trusted network.

1. Lines have no length limit. LinesCodec::new() buffers until it sees a newline. A client that sends gigabytes without one makes the server allocate gigabytes. Fix: LinesCodec::new_with_max_length(8 * 1024), which errors on an oversized line instead.

2. Usernames aren't validated. The protocol separates fields with | and ,, and a username can contain both. A user called a,b shows up as two people. Duplicates collide too: if two clients join as alice, the first to leave removes alice from the list while the other is still connected. Reject empty, reserved (SYSTEM), duplicate and delimiter-containing names before registering.

3. Slow clients lose messages silently. The channel holds 1,024 messages. A client that falls that far behind gets Err(RecvError::Lagged(n)) from rx.recv(). The Ok(msg) = pattern doesn't match an error, so the branch is skipped and the client misses n messages without a trace. Handle Lagged and send a SYSTEM notice.

4. The client only dials localhost. The server binds 0.0.0.0, but the client connects to 127.0.0.1:8080. Chatting across two machines means editing the source. An address argument fixes the most common question about the project.

Takeaways

Broadcast channel plus select! is the core of many real servers, from chat to live dashboards. Writing it by hand made three things concrete: a TCP stream needs explicit framing, every buffer needs a limit, and a pattern like Ok(msg) = rx.recv() can hide an error path. All four fixes are small. Until they're in, this stays a learning project.