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.
| Field | Type | Description |
|---|---|---|
address | string | Canonical textual address, such as "192.0.2.10" or "2001:db8::10". |
family | string | Address family: "IPv4" or "IPv6". |
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.
| Field | Type | Description |
|---|---|---|
ip | IpAddress | The parsed IPv4 or IPv6 address. |
port | u16 | Port number from 0 through 65535. |
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.
| Field | Type | Description |
|---|---|---|
data | u8[] | Datagram payload, truncated to the maxBytes requested by receiveFrom. |
address | string | Sender socket address, such as "127.0.0.1:50000". |
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.
| Field | Type | Description |
|---|---|---|
code | string | Stable machine-readable code, such as "ERR_NET_TIMEOUT". |
message | string | Human-readable explanation of the failure. |
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.
| Method | Signature | Description |
|---|---|---|
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 | () => string | Returns the bound local address. |
close | () => void | Closes the socket and interrupts pending receives. |
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.
| Method | Signature | Description |
|---|---|---|
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 | () => string | Returns the local socket address. |
peerAddress | () => string | Returns 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 | () => void | Closes the stream and interrupts pending I/O. |
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.
| Method | Signature | Description |
|---|---|---|
accept | (timeoutMs?: u64) => Promise<Result<TcpStream, NetError>> | Accepts the next connection. |
localAddress | () => string | Returns the bound listening address. |
close | () => void | Closes the listener and interrupts pending accepts. |
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
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();
}