Skip to content
Kavachकवच

Sockets: UDP

● Intermediate2 min

UDP sends datagrams: single messages with no connection, fast, but each may be lost, doubled or come out of order.

use std.net

fn main() ! Error {
    const server = try net.bind("127.0.0.1:0")
    const client = try net.bind("127.0.0.1:0")
    try client.send("ping".bytes(), server.address())
    const got = try server.receive()
    print("{got.data.text() ?? "?"} from the client: {got.from == client.address()}")
    try server.send("pong".bytes(), got.from)
    print((try client.receive()).data.text() ?? "?")
}

The program ran and printed:

kavach run udp.kav

ping from the client: truepong
udp.kav: Kavach code, then what running it prints

Each datagram says who sent it, in from, so a server can answer. Use UDP where a late answer is worthless anyway, as in games and live audio; use TCP or QUIC when every byte must arrive.