Under heavy development. This site describes the intended 1.0 language. Current features and performance vary. Development status
Sn50SnThe SnAPI programming language
Development · Evolving reference

UdpSocket

Owns one nonblocking UDP socket with exactly-once close authority. TryBind acquires native resources transactionally. Immediate SendTo/ReceiveFrom never wait for readiness and may report WouldBlock. UDP preserves packet boundaries; partial consumption is a marked receipt, never a stream fragment. Mutable receiver loans serialize activity/close; sharing across threads needs external synchronization. Move construction transfers authority and closes the source. Destruction closes without flush and cannot report native close failure. Explicit Close retires the token before native activity and can report errors.

Sn is under heavy development. This reference includes the intended 1.0 design; features may be incomplete in the current compiler. Read the status →

Module std.net

import std.net;

Public declaration contracts and authored examples. A page can document several related symbols. Implementation bodies are excluded.

UdpSocket

pub final class UdpSocket

Owns one nonblocking UDP socket with exactly-once close authority. TryBind acquires native resources transactionally. Immediate SendTo/ReceiveFrom never wait for readiness and may report WouldBlock. UDP preserves packet boundaries; partial consumption is a marked receipt, never a stream fragment. Mutable receiver loans serialize activity/close; sharing across threads needs external synchronization. Move construction transfers authority and closes the source. Destruction closes without flush and cannot report native close failure. Explicit Close retires the token before native activity and can report errors.

Example

module example.udp_socket;
from std.net import UdpSocket, Address, Endpoint, NetworkFailure;
fn Main() -> i32 {
    let Local = Endpoint.Create(Address.CreateIPv4(127_byte, 0_byte, 0_byte, 1_byte), 0_u16);
    var Socket = {
        // Scoped writable carriers end immediately after explicit payload transfer.
        var SocketCreation = UdpSocket.TryBind(Local);
        switch SocketCreation {
            case .Ok { Value = Value: mut UdpSocket& } => break move(Value);
            case .Err => return 1;
        }
    };
    let Bound = switch Socket.ReadLocalEndpoint() { case .Ok { Value = Value } => break Value; case .Err => return 2; };
    if Bound.Port == 0 || !Bound.Address.IsLoopback { return 3; }
    var Moved = move(Socket);
    if !Socket.IsClosed || Moved.IsClosed { return 4; }
    let Input: byte[2] = [0xA1_byte, 0xB2_byte];
    switch Moved.SendTo(Bound, Input) { case .Ok { Value = Count } => { if Count != 2 { return 5; } } case .Err => return 6; }
    var Output: byte[1] = [0_byte];
    switch Moved.ReceiveFrom(Output) {
        case .Ok { Value = Receipt } => {
            if Receipt.Count != 1 || !Receipt.IsTruncated || Receipt.Sender.Port != Bound.Port || Output[0] != 0xA1_byte { return 7; }
        }
        case .Err { Error = PatternPayload5081 } => {
            switch PatternPayload5081 {
                case .Failure { Reason = PatternPayload5082 } if (PatternPayload5082 is .WouldBlock) => {} // One immediate attempt; readiness is separate.
                default => return 8;
            }
        }
    }
    if Moved.Close() is .Err { Error = _ } { return 9; }
    if !Moved.IsClosed || Moved.Close() is .Err { Error = _ } { return 10; }
    switch Moved.SendTo(Bound, Input) {
        case .Err { Error = PatternPayload5083 } => {
            switch PatternPayload5083 {
                case .Failure { Reason = PatternPayload5084, Transferred = Count } if (PatternPayload5084 is .Closed) => { if Count != 0 { return 11; } }
                default => return 12;
            }
        }
        default => return 12;
    }
    return 0;
}

UdpSocket.init

pub init()

Creates a closed owner without native effects.

UdpSocket.init

pub init(Source: readonly Self&) = delete;

Rejects duplicated close authority. Source: Existing owner.

UdpSocket.init

pub init(Source: mut Self&&)

Transfers authority without native I/O; source becomes closed. Source: Writable source consumed by movement.

UdpSocket.operator

pub fn operator =(Source: readonly Self&) -> void = delete;

Rejects copying close authority. Source: Existing owner. Return: No runtime result; this assignment is deleted and cannot be invoked.

UdpSocket.operator

pub fn operator =(Source: mut Self&&) -> void = delete;

Requires explicit close before replacement. Source: Existing owner. Return: No runtime result; this assignment is deleted and cannot be invoked.

UdpSocket.IsClosed

pub IsClosed: bool;

Observes closed/moved state without native activity. Return: True when no close authority is held.

UdpSocket.TryBind

pub static fn TryBind(Local: Endpoint) -> Result<Self, NetworkError>

Creates a numeric local binding, including ephemeral port zero. Local: Owned numeric endpoint copied through native bind. Return: Sole UDP owner or portable failure; failed bind releases opened socket. Warning: Acquires native resources; no DNS or readiness wait.

UdpSocket.ReadLocalEndpoint

pub fn ReadLocalEndpoint() -> Result<Endpoint, NetworkError>

Copies the bound endpoint, including host-selected ephemeral port. Return: Owned numeric endpoint or Closed/native failure; no name lookup.

UdpSocket.SendTo

pub fn SendTo(Remote: Endpoint, Input: readonly byte[]) -> Result<usize, NetworkError>

Attempts one complete packet send, including an empty packet. Remote: Numeric destination copied through return; requires nonzero port. Input: Borrowed bytes retained only through return; zero length is a packet. Return: Accepted packet byte count or typed no-progress/native failure.

UdpSocket.ReceiveFrom

pub fn ReceiveFrom(Output: mut byte[]) -> Result<DatagramReceipt, NetworkError>

Attempts one packet receive into an exclusive initialized destination. Output: Writable bytes; only received prefix is changed. Empty capacity still consumes a packet and marks truncation when it had nonempty payload. Return: Copied sender/count/truncation receipt or typed failure, including WouldBlock.

UdpSocket.SendToAsync

pub async fn SendToAsync(Remote: Endpoint, Input: readonly byte[], Token: CancellationToken) -> Task<Result<usize, NetworkError>>

Sends one complete datagram, awaiting write readiness if needed. Remote: Copied numeric peer with nonzero port. Input: Readonly packet backing retained through completion; empty is a packet. Token: Owned cancellation observation. Return: Accepted packet length or typed failure; no hidden packet splitting.

UdpSocket.SendToAsync

pub fn SendToAsync(mut Remote: Endpoint, Input: readonly byte[]) -> Task<Result<usize, NetworkError>>

Supplies the omitted arguments to SendToAsync. Note: Defaults: Token = CancellationToken(). Remote: Same input, ownership and lifetime contract as the full operation. Input: Same input, ownership and lifetime contract as the full operation. Return: Exact full-operation result; no additional async frame is created.

UdpSocket.SendToAsync

pub async fn SendToAsync(Remote: Endpoint, Input: readonly byte[], Limit: Deadline, Token: CancellationToken) -> Task<Result<usize, NetworkError>>

Performs one bounded transfer against an unchanged absolute deadline. Remote: Copied numeric packet destination. Input: Readonly backing retained through completion. Limit: Finite compatible monotonic boundary or Endless; no retry resets it. Token: Owned cancellation observation checked before expiry. Return: Exact transfer/receipt or typed timeout/domain/cancellation/native failure.

UdpSocket.SendToAsync

pub fn SendToAsync(mut Remote: Endpoint, Input: readonly byte[], mut Limit: Deadline) -> Task<Result<usize, NetworkError>>

Supplies the omitted arguments to SendToAsync. Note: Defaults: Token = CancellationToken(). Remote: Same input, ownership and lifetime contract as the full operation. Input: Same input, ownership and lifetime contract as the full operation. Limit: Same input, ownership and lifetime contract as the full operation. Return: Exact full-operation result; no additional async frame is created.

UdpSocket.ReceiveFromAsync

pub async fn ReceiveFromAsync(Output: mut byte[], Token: CancellationToken) -> Task<Result<DatagramReceipt, NetworkError>>

Receives one packet, preserving copied sender and truncation identity. Output: Exclusive initialized destination retained through completion; zero capacity still consumes a packet and reports truncation when appropriate. Token: Owned cancellation observation. Return: Packet receipt or typed failure; WouldBlock waits rather than returns a fake packet.

UdpSocket.ReceiveFromAsync

pub fn ReceiveFromAsync(Output: mut byte[]) -> Task<Result<DatagramReceipt, NetworkError>>

Supplies the omitted arguments to ReceiveFromAsync. Note: Defaults: Token = CancellationToken(). Output: Same input, ownership and lifetime contract as the full operation. Return: Exact full-operation result; no additional async frame is created.

UdpSocket.ReceiveFromAsync

pub async fn ReceiveFromAsync(Output: mut byte[], Limit: Deadline, Token: CancellationToken) -> Task<Result<DatagramReceipt, NetworkError>>

Performs one bounded transfer against an unchanged absolute deadline. Output: Exclusive initialized backing retained through completion. Limit: Finite compatible monotonic boundary or Endless; no retry resets it. Token: Owned cancellation observation checked before expiry. Return: Exact transfer/receipt or typed timeout/domain/cancellation/native failure.

UdpSocket.ReceiveFromAsync

pub fn ReceiveFromAsync(Output: mut byte[], mut Limit: Deadline) -> Task<Result<DatagramReceipt, NetworkError>>

Supplies the omitted arguments to ReceiveFromAsync. Note: Defaults: Token = CancellationToken(). Output: Same input, ownership and lifetime contract as the full operation. Limit: Same input, ownership and lifetime contract as the full operation. Return: Exact full-operation result; no additional async frame is created.

UdpSocket.Close

pub fn Close() -> Result<void, NetworkError>

Retires close authority once; already closed is an immediate success. Return: Native close completion/failure; authority is consumed on either outcome.

Documentation snapshot: October 24, 2026 About versions ↗
Searching Development · language & standard library