Skip to content

The book · 09

Network channels

book.md · 59 lines · 2 min read

Goal: see that communication over the network is the same Channel[T] as local processes (the language’s native typed RPC), and understand the Serializable constraint.

Two processes in the same runtime are isolated worlds that talk over a channel. Two runtimes on different machines are just two more isolated worlds, and the communication is the same concept. There is no network channel type: it is the same old Channel[T], obtained by a net operation that imposes what physics requires.

Physics requires two things, and both already exist in the language:

  1. The payload has to become bytes, so the operation asks for T + Serializable (chapter 11). Sending something non-serializable over the network does not compile.
  2. Establishing can fail, so the operation returns Result, and the channel inherits the mandatory timeout of the sync.
use net
// server: listens, each connection becomes a Channel[T]
listener := net.listen("0.0.0.0:8080") catch |e| { return e }
loop {
chan := net.accept[Message](listener) catch |e| { continue } // Message: Serializable
spawn handle(chan) // each client = a process
}
// client: connects, gets the Channel[T]
chan := net.connect[Message]("api.example:8080") catch |e| { return e }
chan <- request // SAME channel API
reply := -> chan timeout(5s) catch |e| { return e } // timeout already mandatory

What you get is an ordinary Channel[Message]: send, -> recv, <->, match/select, catch, all identical to chapter 06. The network did not add a communication model; it reused the whole channel and let physics (serialization, failure) express itself through the constraint and the Result.

Since both sides share T at compile time, the network channel is a typed RPC, with no IDL and no generated stub: you send a language value and the other side receives the same type. (To talk to the world that is not yours, whose contract is the wire format and not a shared T, the path is HTTP, through the official http lib, chapter 12.)

For protocols that don’t speak your serialization, net also has layer 2, with TcpStream/ UdpSocket (bytes) that satisfy Readable/Writeable, and thin TLS on top. It is on that layer that http is built.

stream := net.dial_tcp("example:80") catch |e| { return e }
io.write_all(stream, pedido_http_cru)

Next: 10 · Comptime and reflection