Skip to content

tyrus:net types ​

tyrus:net exports structured address and packet values, structured recoverable errors, and explicit TCP and UDP handles.

Types must be imported by name

IpAddress, SocketAddress, UdpPacket, UdpSocket, TcpStream, TcpListener, and NetError must be imported explicitly whenever their fields or methods are used.

IpAddress ​

IpAddress is returned by parseIpAddress(). It represents one validated IPv4 or IPv6 address.

FieldTypeDescription
addressstringCanonical textual address, such as "192.0.2.10" or "2001:db8::10".
familystringAddress family: "IPv4" or "IPv6".
tyrus
import { IpAddress, parseIpAddress } from "tyrus:net";

const address: IpAddress? = parseIpAddress("192.0.2.10");
if (address) {
    print(address.address, address.family); // "192.0.2.10", "IPv4"
}

SocketAddress ​

SocketAddress is returned by parseSocketAddress(). It combines a validated IP address with its port.

FieldTypeDescription
ipIpAddressThe parsed IPv4 or IPv6 address.
portu16Port number from 0 through 65535.
tyrus
import { SocketAddress, parseSocketAddress } from "tyrus:net";

const endpoint: SocketAddress? = parseSocketAddress("[2001:db8::10]:443");
if (endpoint) {
    print(endpoint.ip.address, endpoint.ip.family, endpoint.port); // "2001:db8::10", "IPv6", 443
}

UdpPacket ​

UdpPacket is returned by UdpSocket.receiveFrom(). It contains one received datagram and its sender address.

FieldTypeDescription
datau8[]Datagram payload, truncated to the maxBytes requested by receiveFrom.
addressstringSender socket address, such as "127.0.0.1:50000".
tyrus
import { NetError, UdpPacket, UdpSocket, udpBind } from "tyrus:net";

async function receive(): Promise<void> {
    const bindResult: Result<UdpSocket, NetError> = await udpBind("127.0.0.1:0");
    match (bindResult) {
        Ok(socket) => {
            const result: Result<UdpPacket, NetError> = await socket.receiveFrom(1024, 1000);
            match (result) {
                Ok(packet) => { print(packet.data.length, packet.address); // 5, "127.0.0.1:50000"
                }
                Err(error) => { printError(error.code); }
            }
            socket.close();
        }
        Err(error) => { printError(error.code); }
    }
}

NetError ​

NetError is the recoverable error type for asynchronous network operations.

NetError is an Error: a catch (error) without an annotation receives it, and error is NetError narrows the binding to it, with every field of NetError.

FieldTypeDescription
codestringStable machine-readable code, such as "ERR_NET_TIMEOUT".
messagestringHuman-readable explanation of the failure.
tyrus
import { NetError, TcpStream, tcpConnect } from "tyrus:net";

async function connect(): Promise<void> {
    const result: Result<TcpStream, NetError> = await tcpConnect("127.0.0.1:1", 100);
    match (result) {
        Ok(stream) => { stream.close(); }
        Err(error) => { print(error.code, error.message); // "ERR_NET_CONNECTION_REFUSED", "the TCP connection was refused"
        }
    }
}

UdpSocket methods ​

UdpSocket is returned by udpBind(). Close it after its final operation; later calls return Err(NetError) with ERR_NET_CLOSED.

MethodSignatureDescription
sendTo(data: u8[], address: string, timeoutMs?: u64) => Promise<Result<u64, NetError>>Sends one datagram and returns the number of bytes sent.
receiveFrom(maxBytes: u32, timeoutMs?: u64) => Promise<Result<UdpPacket, NetError>>Receives one datagram and its sender address.
setBroadcast(enabled: boolean) => Promise<void>Enables or disables broadcast transmission.
setTtl(ttl: u32) => Promise<void>Sets IP TTL; valid values are 1 through 255.
localAddress() => stringReturns the bound local address.
close() => voidCloses the socket and interrupts pending receives.
tyrus
import { NetError, UdpSocket, udpBind } from "tyrus:net";

async function useUdp(): Promise<Result<void, NetError>> {
    const socket: UdpSocket = (await udpBind("127.0.0.1:0"))?;
    (await socket.setBroadcast(false))?;
    (await socket.setTtl(64))?;
    const sent: u64 = (await socket.sendTo([104, 101, 108, 108, 111], "127.0.0.1:9000", 1000))?;
    print(socket.localAddress(), sent); // "127.0.0.1:random-port", 5
    socket.close();
    return Ok();
}

TcpStream methods ​

TcpStream is returned by tcpConnect() and TcpListener.accept(). Close it after its final operation.

MethodSignatureDescription
read(maxBytes: u32, timeoutMs?: u64) => Promise<Result<u8[], NetError>>Reads up to maxBytes; EOF is an empty array.
write(data: u8[], timeoutMs?: u64) => Promise<Result<u64, NetError>>Writes bytes and returns the number written.
shutdown() => Promise<Result<void, NetError>>Closes the write side while retaining the read side.
localAddress() => stringReturns the local socket address.
peerAddress() => stringReturns the remote socket address.
stream() => Promise<Result<DuplexStream<u8[], u8[]>, NetError>>Hands the connection to a bounded byte duplex; closing its writable side shuts down only the write direction. Afterwards read, write and shutdown return Err(NetError) with ERR_NET_STREAMED.
close() => voidCloses the stream and interrupts pending I/O.
tyrus
import { NetError, TcpStream, tcpConnect } from "tyrus:net";

async function useTcp(): Promise<Result<void, NetError>> {
    const stream: TcpStream = (await tcpConnect("127.0.0.1:8080", 1000))?;
    const written: u64 = (await stream.write([104, 105], 1000))?;
    const data: u8[] = (await stream.read(1024, 1000))?;
    (await stream.shutdown())?;
    print(stream.localAddress(), stream.peerAddress(), written, data.length); // "127.0.0.1:random-port", "127.0.0.1:8080", 2, 2
    stream.close();
    return Ok();
}

TcpListener methods ​

TcpListener is returned by tcpListen(). Close it after it stops accepting connections.

MethodSignatureDescription
accept(timeoutMs?: u64) => Promise<Result<TcpStream, NetError>>Accepts the next connection.
localAddress() => stringReturns the bound listening address.
close() => voidCloses the listener and interrupts pending accepts.
tyrus
import { NetError, TcpListener, TcpStream, tcpListen } from "tyrus:net";

async function acceptOne(): Promise<Result<void, NetError>> {
    const listener: TcpListener = (await tcpListen("127.0.0.1:0", 1000))?;
    print(listener.localAddress()); // "127.0.0.1:random-port"
    const stream: TcpStream = (await listener.accept(1000))?;
    print(stream.peerAddress()); // "127.0.0.1:random-port"
    stream.close();
    listener.close();
    return Ok();
}

Error handling ​

error

tyrus
import { NetError, UdpSocket, udpBind } from "tyrus:net";

async function useClosedSocket(): Promise<Result<void, NetError>> {
    const socket: UdpSocket = (await udpBind("127.0.0.1:0"))?;
    socket.close();
    const result: Result<UdpPacket, NetError> = await socket.receiveFrom(32, 1000);
    match (result) {
        Ok(_) => {}
        Err(error) => { print(error.code); // "ERR_NET_CLOSED"
        }
    }
    return Ok();
}