// Reference program (Phase 3 exit, in source): TCP echo with tasks over the // deterministic loopback. A server task accepts two connections and spawns one echo // task per connection; two client tasks share the address and the message through // shared loans. The bytes echoed to both clients: 2 × (112+105+110+103) = 860. // expect: run // grant: listen=net.listen // grant: connect=net.connect // schedules: 30 // quantum: 5 // result: 860 // equivalent: phase3/run/program_tcp_echo_tasks.air // phase: 6 // spec: docs/spec/15-source-language.md module demo.tcpechotasks // Receives up to 4 bytes and sends them back, then closes the stream. fn echo(s: stream) -> u8 effects [net.read, net.write] { var buf: [u8; 4] = zero; let n = net.recv(s, mut buf) or trap; net.send_all(s, ref buf[0..n]) or trap; net.close_stream(move s) or trap; 0 } // Accepts two connections; each is moved into its own echo task. fn serve(l: listener) -> u8 effects [net.listen, net.read, net.write, task.spawn] { scope sc { let s1 = net.accept(l) or trap; let t1 = task.spawn(sc, echo, move s1); let s2 = net.accept(l) or trap; let t2 = task.spawn(sc, echo, move s2); task.join(move t1); task.join(move t2); } net.close_listener(move l) or trap; 0 } // Connects, sends the message, and returns the sum of the bytes echoed back. fn client(connect: cap, addr: slice, msg: slice) -> u64 effects [net.connect, net.read, net.write] { var back: [u8; 4] = zero; let c = net.connect(connect, addr) or trap; net.send_all(c, msg) or trap; let n = net.recv(c, mut back) or trap; net.close_stream(move c) or trap; var acc: u64 = 0; for i in 0..n { acc = acc + back[i] as u64; } acc } fn main(listen: cap, connect: cap) -> u64 effects [net.listen, net.connect, net.read, net.write, task.spawn] { let addr_bytes = b"127.0.0.1:7"; let ping_bytes = b"ping"; ref addr = addr_bytes; ref ping = ping_bytes; let l = net.listen(listen, addr) or trap; var sum: u64 = 0; scope sc { let srv = task.spawn(sc, serve, move l); let c1 = task.spawn(sc, client, connect, addr, ping); let c2 = task.spawn(sc, client, connect, addr, ping); task.join(move srv); let a = task.join(move c1); let b = task.join(move c2); sum = a + b; } sum }