Skip to main content
Be Bitwise
RustAsync & Networking

TCP in Rust

The standard library handles synchronous TCP out of the box. Async TCP is Tokio's territory.

Synchronous TCP Client

rust
use std::net::TcpStream;
use std::io::{Read, Write};
fn main() -> std::io::Result<()> {
let mut stream = TcpStream::connect("127.0.0.1:8080")?;
stream.write_all(b"Hello, server!")?;
let mut buffer = [0u8; 1024];
let n = stream.read(&mut buffer)?;
println!("Response: {}", String::from_utf8_lossy(&buffer[..n]));
Ok(()) // stream is dropped here, connection closed
}

Synchronous TCP Server

rust
use std::net::TcpListener;
use std::io::{Read, Write};
fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080")?;
println!("Listening on port 8080");
for stream in listener.incoming() {
let mut stream = stream?;
let mut buffer = [0u8; 1024];
let n = stream.read(&mut buffer)?;
let response = format!("Echo: {}", String::from_utf8_lossy(&buffer[..n]));
stream.write_all(response.as_bytes())?;
}
Ok(())
}

Both of these treat one read as one message, which only works because the messages are tiny and the test runs on one machine. TCP is a byte stream with no message boundaries: the client's 14 bytes can arrive as one read of 14, or a read of 3 followed by a read of 11, and two quick writes can land in a single read. Real protocols frame their data, with a length prefix or a delimiter such as a newline, and keep reading until a whole message has arrived (read_exact, or BufReader::read_line).

Key Concept

Ownership pulls its weight in networking too. TcpStream implements Drop, so the socket closes the moment it falls out of scope. No close() call to forget, no leaked file descriptors haunting your process.

Async TCP with Tokio

rust
use tokio::net::{TcpListener, TcpStream};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("Listening on port 8080");
loop {
let (socket, addr) = listener.accept().await?;
println!("New connection from {}", addr);
tokio::spawn(async move {
handle_client(socket).await;
});
}
}
async fn handle_client(mut socket: TcpStream) {
let mut buffer = [0u8; 1024];
loop {
let n = match socket.read(&mut buffer).await {
Ok(0) => return, // connection closed
Ok(n) => n,
Err(_) => return,
};
if socket.write_all(&buffer[..n]).await.is_err() {
return;
}
}
}

Async vs Threads

ApproachMemory per connectionSwitching costBest for
Thread-per-client1-8 MB of stack address space, plus the pages it touchesOS context switchHundreds of clients
Async tasks~few KBCooperative yieldThousands of clients

Here's where that memory actually sits. With threads, every connection gets an OS thread and its own stack (Rust's default for spawned threads is 2 MiB of reserved address space, most of it never touched). With Tokio, every connection gets a task, and a task is just the future struct for handle_client: its locals, including that 1 KB buffer, plus a little bookkeeping. A handful of worker threads take turns polling whichever tasks are ready:

Each client gets its own lightweight task. A task's state lives in its future on the heap for its whole life, and it borrows a worker thread's stack only while it's being polled, so ten thousand idle connections cost ten thousand small futures and nothing more.

Error Handling

Result slots in without ceremony:

rust
async fn handle_client(mut socket: TcpStream) -> Result<(), Box<dyn std::error::Error>> {
let mut buffer = vec![0u8; 4096];
let n = socket.read(&mut buffer).await?;
let request = String::from_utf8_lossy(&buffer[..n]);
println!("Received: {}", request);
socket.write_all(b"OK\n").await?;
Ok(())
}

Every I/O call hands back a Result. The ? operator bubbles errors up the stack — no try/catch scaffolding required.