Lyricdev
GitHub

std.net

The network: IP addresses (IpAddr) and socket addresses (SocketAddr), TCP — a TcpListener that accepts, a TcpStream that is a Reader and a Writer —, UDP (UdpSocket), and name resolution (resolve).

A call that would block parks the task until the thread's poller says the socket is ready, then tries again; a cancel ends that wait with Cancelled, and a close — on any thread — with Closed. There are no socket timeouts: withTimeout bounds a call instead. On POSIX the sockets are polled with epoll or kqueue; on Windows they use Winsock, with an AFD poll request per socket on the thread's completion port.

Examples

Compiles; not run here

import std.net { TcpListener, SocketAddr };

fn main(): void throws Error {
    let listener = try TcpListener.bind(SocketAddr.parse("127.0.0.1:8080"));
    let stream = try listener.accept();
    try stream.write("hello\n".bytes());
    try stream.close();
}

Types

IpAddr enum — An IP address: version 4's four bytes, or version 6's eight groups of 16 bits.
SocketAddr struct — An IP address and a port.
TcpListener class — A listening TCP socket: bind creates it, accept returns each incoming connection as a TcpStream.
Shutdown enum — How much of a stream TcpStream.shutdown ends: its reading, its writing, or both.
TcpStream class — A TCP connection: a Reader and a Writer whose calls wait for the socket — a read until bytes come, a write until the system takes some.
UdpSocket class — A UDP socket: datagrams sent to an address, and received with their sender's.

Functions

pub fn resolve(host: StringView): List<IpAddr> throws IoError

Returns the addresses host names: a name the system's resolver knows — localhost, example.org — or an address's own text; each address once, in the resolver's order. It runs on the I/O pool, as a file's call does, so it is not a point of cancellation: a cancel shows at the task's next wait.

Errors

Throws IoError with the name as the path: NotFound for a name nobody knows, else the resolver's failure.