TCP Echo Server With TcpListener

Accept loopback clients with TcpListener, echo each line from a cloned writer, and close cleanly when the peer drops the connection.

RustData Fetching

Code

rustsnippet
35 lines
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;

fn main() -> std::io::Result<()> {
    // 端口 0:由内核分配空闲端口
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let addr = listener.local_addr()?;
    println!("listening on {addr}");

    let server = thread::spawn(move || -> std::io::Result<()> {
        let (stream, peer) = listener.accept()?;
        let mut writer = stream.try_clone()?;
        let reader = BufReader::new(stream);
        for line in reader.lines() {
            let line = line?;
            // 原样回写,行协议以换行结尾
            writeln!(writer, "echo: {line}")?;
        }
        println!("connection closed by {peer}");
        Ok(())
    });

    let mut client = TcpStream::connect(addr)?;
    client.write_all(b"ping\nsecond\n")?;
    let mut replies = BufReader::new(client);
    for _ in 0..2 {
        let mut line = String::new();
        replies.read_line(&mut line)?;
        println!("client got: {}", line.trim_end());
    }
    drop(replies); // 关闭连接,让服务端读到 EOF
    server.join().unwrap()?;
    Ok(())
}

How the snippet works

Count the function main as the entire surface area of TCP Echo Server With TcpListener.

Repetition is confined to for line in reader.lines() — the rest of the file is straight-line. Result is the error channel: the caller receives the failure as a value instead of an exception.

Points of care

  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Using it

The primary signature is fn main() -> std::io::Result<()>

The output lines announce the steps: listening on, connection closed by, client got:.

Key statements

server.join().unwrap()?;
let listener = TcpListener::bind("127.0.0.1:0")?;
let mut client = TcpStream::connect(addr)?;

Interactive Tools for This Topic

FAQ

What happens when a call fails?
Each fallible operation returns `Result`; nothing is silently discarded.
What does TCP Echo Server With TcpListener print when run?
No setup needed: run the file and look for labeled lines like `listening on`, `connection closed by`, `client got:` in the output.