Rust Reference ยท Standard Library Modules
Rust TcpListener and TcpStream types
Reference for std::net TcpListener and TcpStream: bind, accept, connect, timeouts, shutdown, read and write semantics, nonblocking mode and building a loopback echo server.
std::net::TcpListener waits for incoming TCP connections on an address, and std::net::TcpStream is one open connection, whether you created it by connecting out or got it from accept. A TcpStream implements Read and Write, so everything you know about files and buffered I/O applies, with the extra rule that TCP is a stream of bytes: message boundaries are not preserved.
The standard library's networking is blocking: accept, read and connect wait until they can finish. You use threads for concurrency, or switch to non-blocking mode, or an async runtime from a crate.
use std::net::TcpListener; let listener = TcpListener::bind("127.0.0.1:0")?; // port 0: the OS picks a free port
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl TcpListener { pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener>; pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)>; pub fn incoming(&self) -> Incoming<'_>; // iterator of io::Result<TcpStream> pub fn local_addr(&self) -> io::Result<SocketAddr>; pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()>; pub fn try_clone(&self) -> io::Result<TcpListener>; } impl TcpStream { pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream>; pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream>; pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()>; pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>; pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()>; pub fn shutdown(&self, how: Shutdown) -> io::Result<()>; pub fn peer_addr(&self) -> io::Result<SocketAddr>; pub fn local_addr(&self) -> io::Result<SocketAddr>; pub fn try_clone(&self) -> io::Result<TcpStream>; pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()>; }
| Name | Description |
|---|---|
addr |
Anything implementing ToSocketAddrs: "127.0.0.1:8080", ("localhost", 80), a SocketAddr. Host names are resolved, which may block. |
timeout |
Some(d) with d > 0 or None for no limit. Duration::ZERO is rejected with InvalidInput. |
Shutdown |
Read, Write or Both. Closing the write half sends a FIN, which the peer sees as end-of-file. |
Returns. accept returns the connected stream and the peer address. read returns Ok(0) when the peer closed its writing side, and may return fewer bytes than the buffer size: loop or use read_exact.
Errors and panics. Typical kinds: ConnectionRefused, AddrInUse (port taken), AddrNotAvailable, TimedOut, WouldBlock (a timeout on Unix, or nothing ready in non-blocking mode), ConnectionReset, BrokenPipe, PermissionDenied (low ports). Nothing here panics.
Usage notes
- No message boundaries. One
writeon the sender can arrive as severalreads, and several writes can arrive as one. Add your own framing: a length prefix, a delimiter such as\n, or a fixed size. - Buffer small writes. Wrap writers in
BufWriterand readers inBufReader, and do not forgetflush. For request/response protocols with tiny writes,set_nodelay(true)disables Nagle's delay. - Close properly. Dropping a stream closes it. Use
shutdown(Write)when you still want to read the answer after telling the peer you are finished. - One thread per connection is simple and fine for hundreds of clients. Beyond that use a thread pool, non-blocking sockets or an async runtime.
- Bind to
127.0.0.1for local-only services.0.0.0.0accepts connections from the network, which is often not what you want in development. - Port 0 gives a free port and
local_addr()tells you which one. That is the reliable way to write tests. - Timeouts are per call.
set_read_timeoutlimits eachread, not the whole conversation. - IPv6.
"[::1]:8080"is the loopback address;ToSocketAddrsfor names may return both families andconnecttries each in turn. - UDP is a separate type,
UdpSocket, with datagrams and boundaries; TLS and HTTP are not in std. - Our runner has no outside network; examples talk to
127.0.0.1only.