TCP (blocking)
A minimal accept-respond loop using std.net.tcp.
This example uses the blocking TCP API in std.net.tcp. Each call blocks the calling thread until the syscall returns. Once the reactor lands, the same calls will gain a suspends effect that lets parked tasks yield the worker without changing the call shape.
import std.net.tcp as tcp
def main() -> i32: let listener_result: Result[tcp.TcpListener, tcp.NetError] = tcp.tcp_listen_ipv4(8080) let mut listener: tcp.TcpListener = match listener_result: Ok(l) => l Err(e) => return 1
use mut stream = try tcp.accept(view listener): let response: view [u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" try tcp.stream_write_all(view stream, response)
return 0What’s worth noticing:
tcp.tcp_listen_ipv4(8080)binds to127.0.0.1:8080. Ports above 65535 short-circuit withInvalidPortbefore touching the OS.use mut stream = try tcp.accept(view listener):: the resource block shorthand. BecauseTcpStreamis a compiler-known std resource withclose_best_effort, the cleanup clause is implicit.mutis required because closing invalidates the handle.try tcp.stream_write_all(view stream, response): write all bytes or propagate the first error. The function loops internally until the buffer is drained.b"HTTP/1.1 ...": a byte-string literal. The value’s type isview [u8].
The listener cleans itself up via its drop destructor at the end of main.
For the full surface (read helpers, error variants, error-recovery patterns), see std.net.tcp.