Skip to content
Kavachकवच

Sockets: Timeouts

● Intermediate2 min

Every network wait gives up after 30 seconds. .timeout(d) sets a shorter or longer deadline for one call.

use std.net
use std.time

fn silent(listener: Listener) ! NetError uses Net, Clock {
    const conn = try listener.accept()
    time.sleep(2.seconds)
    conn.close()
}

fn main() ! Error {
    const listener = try net.listen("127.0.0.1:0")
    const _server = spawn silent(listener)
    const conn = try net.connect(listener.address())
    const data = conn.read().timeout(200.ms) catch e => match e {
        NetError.TimedOut(_) => {
            print("no answer within 200 ms: gave up")
            return
        }
        _ => fail e,
    }
    print(data)
}

The program ran and printed:

kavach run timeout.kav

no answer within 200 ms: gave up
timeout.kav: Kavach code, then what running it prints

The server here never answers. Without a deadline a program could wait forever for it; with one, the call fails with TimedOut and the program decides what to do.