Of course! Here is a simple TCP server in Rust using Tokio.
This example will handle one client at a time. It will accept a connection, read a single message, write a response, and then close the connection. Only after the first client is fully handled will it be ready to accept a new one. This demonstrates the core async/await flow without the concurrency of tokio::spawn.
Prerequisites
You need to have Rust installed. Then, create a new project:
cargo new tokio-sequential-server
cd tokio-sequential-server
Cargo.toml
Add tokio to your dependencies with the full feature flag to enable all its components, including networking and I/O.
[package]
name = "tokio-sequential-server"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
src/main.rs
This is the complete server code.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use std::error::Error;
/// The main function sets up the server.
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// 1. Bind a TcpListener to a socket address.
let listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("✅ Server listening on 127.0.0.1:8080");
// 2. Enter the main server loop.
// This loop will accept one connection at a time.
loop {
// 3. Wait for a new connection.
// The `.await` pauses the loop until a client connects.
let (stream, addr) = listener.accept().await?;
println!("➡️ Accepted connection from: {}", addr);
// 4. Handle the connection.
// We pass the new stream to our handler function.
// The `await` here is crucial: the loop will not continue to
// accept new connections until `handle_connection` has finished.
if let Err(e) = handle_connection(stream).await {
println!("❌ Failed to handle connection: {}", e);
}
}
}
/// Handles a single client connection.
async fn handle_connection(mut stream: TcpStream) -> Result<(), Box<dyn Error>> {
let mut buffer = [0; 1024]; // A 1KB buffer
// Read data from the stream.
let bytes_read = stream.read(&mut buffer).await?;
// If the client sends no data and closes the connection, `bytes_read` will be 0.
if bytes_read == 0 {
println!("ℹ️ Client closed the connection without sending data.");
return Ok(());
}
// Print the received message.
let received_data = String::from_utf8_lossy(&buffer[..bytes_read]);
println!("📥 Received: {}", received_data.trim());
// Write a response back to the client.
let response = b"Hello from server! Message received.\n";
stream.write_all(response).await?;
println!("📤 Sent response to client.");
// The stream will be closed automatically when it goes out of scope here.
println!("✅ Connection with {} handled successfully.", stream.peer_addr()?);
Ok(())
}
How to Run and Test
-
Run the Server:
Open a terminal, navigate to your project directory, and run:
cargo run
You will see the message: ✅ Server listening on 127.0.0.1:8080.
-
Test with a Client (like netcat or telnet):
Open a second terminal and use netcat (or nc) to connect to your server.
# The -N flag tells netcat to close the connection after EOF
# which is useful for testing this server.
netcat -N 127.0.0.1 8080
Now, type a message and press Enter:
Hello, world!
The client (netcat) will receive the server's response and then exit:
Hello from server! Message received.
In your server's terminal, you will see the full log of the interaction:
➡️ Accepted connection from: 127.0.0.1:54321 (port will vary)
📥 Received: Hello, world!
📤 Sent response to client.
✅ Connection with 127.0.0.1:54321 handled successfully.
Code Breakdown (The "No spawn" Logic)
-
#[tokio::main]: This macro sets up the Tokio async runtime, allowing us to use async/await.
-
TcpListener::bind(...).await: This creates a listener that is bound to the specified IP address and port. It's an async operation, so we .await it.
-
loop { ... }: This is the main server loop. It runs forever, waiting for new connections.
-
listener.accept().await: This is the most important line for understanding the sequential flow. The code pauses here and yields control back to the Tokio runtime. The loop will not proceed until a client connects. When a connection is established, accept() returns a tuple containing the TcpStream (for communication) and the client's address.
-
handle_connection(stream).await: This is the key difference from a concurrent server.
- We call our
async handler function, which contains all the logic for reading and writing.
- Because we use
.await on the result of handle_connection, the main server loop is blocked.
- The
loop will not iterate again (and thus cannot accept() a new connection) until handle_connection has completely finished its work (read the data, wrote the response, and returned).
This architecture is simple and easy to understand but can only serve one client at a time. If a second client tries to connect while the first is being handled, its connection request will be queued up by the operating system until the server's accept() call is ready for it. To handle multiple clients concurrently, you would wrap the call to handle_connection in tokio::spawn.