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.
Code
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
Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
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
DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.IPv4 Subnet CalculatorCalculate network and broadcast addresses, netmask, wildcard, and usable host range from an IPv4 address in CIDR notation.Port Number LookupLook up common well-known TCP and UDP ports by number or by service name, with the port range class.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.