Below is a simple example of a TCP server written in Rust using the Tokio library. This server will listen on port 8080 and echo back any message it receives from a client. Notably, this example does not use tokio::spawn to handle each incoming connection asynchronously in the background. Instead, it sequentially handles connections one by one in a single task, which is not suitable for production use but serves as a good educational example to understand the basics.
First, ensure you have Tokio in your Cargo.toml:
[package]
name = "simple_tcp_server"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
Then, here's the simple TCP server code (src/main.rs):
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("Server listening on localhost:8080");
loop {
// Instead of spawning a new task for each connection,
// we await the accept call, handling connections sequentially.
let (mut socket, _) = listener.accept().await?;
println!("New connection established!");
// Handle the connection directly in this task.
handle_connection(&mut socket).await?;
}
}
async fn handle_connection(socket: &mut TcpStream) -> Result<(), std::io::Error> {
let mut buf = [0; 512]; // Buffer to store incoming data
loop {
// Read data from the socket
let n = socket.read(&mut buf).await?;
if n == 0 {
// If `read` returns 0, it means the client disconnected.
println!("Client disconnected.");
return Ok(());
}
println!("Received: {}", String::from_utf8_lossy(&buf[0..n]));
// Echo the data back to the client
socket.write_all(&buf[0..n]).await?;
// Flush ensures the data is sent immediately
socket.flush().await?;
}
}
Here's a breakdown of what this code does:
-
main Function:
- The
#[tokio::main] macro sets up a Tokio runtime and converts the main function into an async function.
- We bind a
TcpListener to 127.0.0.1:8080, starting our server.
- The server enters a loop, waiting for incoming connections with
listener.accept().await?. This call is blocking in the sense that it won't proceed until a new connection is established.
-
Handling Connections:
- Once a connection is accepted, we get a
TcpStream representing the connection.
handle_connection function: This is where the actual communication with the client happens. It reads from the socket into a buffer, prints the received message, and then echoes the message back to the client.
- The
read and write_all calls are asynchronous, meaning they yield control back to the Tokio runtime while waiting for I/O operations to complete, allowing other tasks (if we had any) to run. However, since we're not spawning new tasks for each connection, we're effectively handling one connection at a time.
-
Sequential Nature:
- Notice that
handle_connection is awaited directly in the main loop. This means the server won't accept new connections until the current handle_connection call completes (i.e., until the client disconnects).
- This is in contrast to a typical production server, which would use
tokio::spawn to start a new task for each connection, allowing the server to handle multiple clients concurrently.
Testing the Server:
- Run the server with
cargo run.
- Use a tool like
telnet (if available) or nc (Netcat) to connect and test:
- With Netcat:
nc localhost 8080
- Type messages and press Enter; you should see them echoed back.
This example illustrates the basics of a Tokio-based TCP server without concurrency through spawn. For a real-world application, you'd likely want to handle each connection in a separate Tokio task to manage multiple clients simultaneously. Here's a hint on how you'd modify the accept loop for concurrent handling:
loop {
let (socket, _) = listener.accept().await?;
tokio::spawn(handle_connection(socket)); // Note: handle_connection would take ownership of socket
}
And adjust handle_connection to not reference socket:
async fn handle_connection(mut socket: TcpStream) -> Result<(), std::io::Error> {
// Same implementation...
}
This way, each connection is handled independently, and your server can serve multiple clients at once.