Use std::net::TcpListener to bind to a port and handle incoming TCP connections in Rust.
Use std::net::TcpListener to bind to an address and iterate over incoming connections with incoming().
use std::net::TcpListener;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
println!("Connection established!");
}
}
std::net sets up a basic server that waits for other programs to connect to it on a specific port. Think of it like a phone line that rings when someone calls; your program answers the call and prints a message. You use this pattern whenever you need to accept network connections in a Rust application.