> module
std::net
TCP, UDP and Unix-domain sockets
std::net provides blocking sockets with a text interface: data is written as strings and read back as strings, with invalid UTF-8 replaced by U+FFFD. Fallible operations return Result with the shared io::Error (see xur.std.io(7)).
Addresses are strings such as "127.0.0.1:8080" or "example.com:80". Binding to port 0 picks a free port.
> types
A TCP socket accepting connections.
TcpListener::bind(address: str) -> Result<TcpListener, Error>Listens for TCP connections on address.
Waits for a connection and returns its stream and the peer's address.
A TCP connection.
Reads what is available, up to max bytes, waiting for at least one. Returns an empty string at the end of the stream.
Reads up to and including the next newline. Returns an empty string at the end of the stream.
A UDP socket.
Waits for a datagram and returns its text and the sender's address. A datagram longer than max bytes is cut short.
Unix-domain sockets exist only on Unix.
A Unix-domain socket accepting connections.
UnixListener::bind(path: str) -> Result<UnixListener, Error>Listens on a Unix-domain socket at path, which must not already exist.
unix_listener.accept() -> Result<UnixStream, Error>Waits for a connection and returns its stream.
A connection over a Unix-domain socket.
UnixStream::connect(path: str) -> Result<UnixStream, Error>Connects to the Unix-domain socket at path.
> examples
use std::io;
use std::net;
use std::thread;
fn main() -> Result<(), io::Error> {
let listener = net::TcpListener::bind("127.0.0.1:0")?;
let addr = listener.local_addr()?;
let client = thread::spawn(|| {
let stream = net::TcpStream::connect(addr).unwrap();
stream.write("hello\n").unwrap();
});
let (stream, peer) = listener.accept()?;
io::println("{} sent {}", peer, stream.read_line()?.trim());
client.join();
Ok(())
}