Skip to content
Hierarchy
rust-realtime-chat.mdx

Building a Real-Time CLI Chat Application in Rust

My rust learning journey on understanding TCP protocol and Rust programming language.

By Ahsan Azizan ยท ยท 4 min read

Rust gives you performance, memory safety, and a concurrency model that catches data races at compile time, which makes it a good fit for network code. To get a firmer grip on it, I built a real-time chat application that runs on the command line over TCP sockets. Here is how it works and what I took away from it.

Project overview

The project has two parts:

  1. A server that accepts multiple client connections and broadcasts messages.
  2. A client that sends messages to the server and displays what the server broadcasts.

Networking comes from Rust's std::net module, and concurrency from threads.

Server implementation

How it works

The server accepts client connections, listens for incoming messages, and broadcasts them to every connected client. Three things make that work:

  • A non-blocking TCP server, so one slow client cannot stall the others.
  • One thread per client, so communication happens simultaneously.
  • A graceful shutdown on CTRL+C.

The code

use std::io::{ErrorKind, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Sender};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

use colored::Colorize;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Server setup code...
}

Handling new client connections

When a client connects, the server spawns a thread for it:

if let Ok((mut socket, addr)) = server.accept() {
    println!("โœ… New Client connected: {}", addr.to_string().yellow());

    let tx = tx.clone();
    clients.push(socket.try_clone().expect("Failed to clone client"));

    thread::spawn(move || {
        let mut buffer = [0; 1024];

        loop {
            match socket.read(&mut buffer) {
                Ok(n) if n == 0 => {
                    println!("๐Ÿ”Œ Client has disconnected: {}", addr);
                    return;
                }
                Ok(n) => {
                    let msg = String::from_utf8_lossy(&buffer[..n]);
                    tx.send(format!("Client {}: {}", addr, msg))
                        .expect("Failed to send message to channel");
                }
                Err(ref err) if err.kind() == ErrorKind::WouldBlock => (),
                Err(e) => {
                    eprintln!("โŒ Connection error: {}", e);
                    return;
                }
            }
            thread::sleep(Duration::from_millis(100));
        }
    });
}

Each thread reads from its own client and pushes what it reads into a channel.

Broadcasting messages

The main loop drains that channel and writes each message to every client. Clients whose write fails are dropped from the list in the same pass:

if let Ok(msg) = rx.try_recv() {
    let broadcast_msg = format!("๐Ÿ“ข Broadcast: {}", msg);

    clients = clients
        .into_iter()
        .filter_map(|mut client| {
            let mut buff = broadcast_msg.clone().into_bytes();
            buff.push(b'\n');

            client.write_all(&buff).map(|_| client).ok()
        })
        .collect();
}

Graceful shutdown

Shutdown uses the ctrlc crate and an AtomicBool that the main loop checks:

let running = Arc::new(AtomicBool::new(true));
let r = running.clone();

ctrlc::set_handler(move || {
    r.store(false, Ordering::SeqCst);
    println!("\n๐Ÿ›‘ Shutting down server...");
})
.expect("Error setting CTRL+C handler");

Client implementation

How it works

The client connects to the server, sends what the user types, and prints what the server broadcasts:

  • Non-blocking I/O, so sending and receiving do not block each other.
  • Input read on its own thread while the main thread listens for server messages.
  • :quit to disconnect.

The code

use std::io::{self, ErrorKind, Read, Write};
use std::net::TcpStream;
use std::sync::mpsc::{self, TryRecvError};
use std::thread;
use std::time::Duration;

use colored::Colorize;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Client setup code...
}

Sending user messages

A separate thread reads stdin and forwards each line to the server:

thread::spawn(move || {
    println!("๐Ÿ’ฌ Enter your messages (type ':quit' to exit)");

    loop {
        let mut buff = String::new();
        io::stdin().read_line(&mut buff).expect("Failed to read from stdin");

        let msg = buff.trim().to_string();
        if msg == ":quit" {
            println!("๐Ÿ‘‹ Exiting chat...");
            break;
        }

        if tx.send(msg).is_err() {
            break;
        }
    }
});

Receiving server messages

The main thread reads from the socket and prints what arrives. A read of zero bytes means the server closed the connection:

match client.read(&mut buff) {
    Ok(n) => {
        if n == 0 {
            println!("๐Ÿ”Œ Server closed the connection");
            break;
        }

        print!("{}", String::from_utf8_lossy(&buff[..n]).green());
    }
    Err(ref err) if err.kind() == ErrorKind::WouldBlock => (),
    Err(_) => {
        println!("โŒ Connection with server was severed");
        break;
    }
}

Lessons learned

Rust's ownership model is the part that fought me hardest and taught me most. Sharing state across threads forced me to be explicit about it, and Arc<AtomicBool> plus channels turned out to be all this program needed.

Error handling pushed me the same way. Non-blocking I/O surfaces WouldBlock constantly, and match on the error kind makes you decide what each case means instead of ignoring it.

TCP does the heavy lifting underneath. Messages arrive in order and without loss, which is what a chat needs, and pairing TCP streams with threads is enough to serve several clients at once.

Running the application

  1. Clone the repository:

    git clone https://github.com/ahsanzizan/rust-realtime-chat.git
    cd rust-realtime-chat
    
  2. Build the project:

    cargo build --release
    
  3. Start the server:

    ./target/release/server
    
  4. Start the client in another terminal:

    ./target/release/client
    

Conclusion

This project did more for my understanding of Rust's ownership model, threading, and error handling than any amount of reading did.

The code is on GitHub if you want to read it or contribute.