Skip to content

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 0

What’s worth noticing:

  • tcp.tcp_listen_ipv4(8080) binds to 127.0.0.1:8080. Ports above 65535 short-circuit with InvalidPort before touching the OS.
  • use mut stream = try tcp.accept(view listener):: the resource block shorthand. Because TcpStream is a compiler-known std resource with close_best_effort, the cleanup clause is implicit. mut is 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 is view [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.