Create an echo server
This tutorial will guide you through creating a simple echo server in Rust.
Install Rust
Run
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
to install the Rust toolchain.
Run
cargo
to verify if it has been installed successfully.
Create the echo server
Run
cargo new --bin echo-server && cd echo-server
to create a new Rust project for the echo server.
Run
cat > src/main.rs <<EOF
use std::env;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
fn handle(mut stream: TcpStream) {
println!("Connection opened: {}", stream.peer_addr().unwrap());
let mut buf = [0; 512];
loop {
match stream.read(&mut buf) {
Ok(0) => {
println!("Connection closed: {}", stream.peer_addr().unwrap());
return;
}
Ok(n) => {
if let Err(e) = stream.write_all(&buf[..n]) {
eprintln!("Failed to write to socket: {}", e);
return;
}
}
Err(e) => {
eprintln!("Failed to read from socket: {}", e);
break;
}
}
}
}
fn main() -> std::io::Result<()> {
let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
let addr = format!("0.0.0.0:{}", port);
let listener = TcpListener::bind(&addr)?;
println!("Echo server listening on {}", addr);
listener
.incoming()
.try_for_each(|stream| -> Result<_, std::io::Error> {
let stream = stream?;
std::thread::spawn(move || {
handle(stream);
});
Ok(())
})
}
EOF
to add the code for the echo server. Feel free to pause and understand how the echo server works.
Test the echo server locally
Run
cargo run
to run the echo server locally.
In a new terminal, run
nc 127.0.0.1 8080
to connect to the echo server. Type anything in the terminal and the echo server should echo it back to you. Type Ctrl+C
to exit both programs.
You can also run the echo server on a different port by specifying the PORT env variable by running
PORT=5000 cargo run
In a new terminal, you can access the server just as above but on 5000
port using
nc 127.0.0.1 5000
Now that you have created the application, the next step is to package it into a Docker image.