TCP and names
Raw TCP is a stream of bytes, not a queue of messages, so these calls move bytes rather than whole messages:
socketServe(port, handler)calls aproc(SocketConnection): voidonce per connection;socketConnect(host, port)connects out and answers with aResult.socketReceive(conn, bytes)answers with up to that many bytes; fewer is normal, not an error.socketReceiveLine(conn)reads up to the next newline and drops it, along with a\rbefore it, and still returns a last line that has no newline.socketSend(conn, data)answers with the number of bytes sent;socketPeer(conn)is the other end, as"host:port";socketClose(conn)closes the stream.
A hive.net.SocketError is Connect, Closed, Send or Receive, each with a message. A peer hanging up gives SocketError.Closed: the normal end of a conversation, not a failure to report.
Two calls deal with names rather than connections. resolve(name) looks up every address behind a host name (a name, not "host:port"), and an address written out resolves to itself. localAddress() is the address another machine would reach this one on, never the loopback, and finding it sends nothing. Their hive.net.NetError is NotFound (nobody registered the name), Lookup (the resolver could not be asked) or NoAddress (this machine has no address but the loopback), each with a message.
proc handle(conn: hive.net.SocketConnection): void {
// One line in, one line back, until the caller hangs up.
for ;; {
got := hive.net.socketReceiveLine(conn)
if got is Result.Ok(line) {
hive.net.socketSend(conn, "you said: {line}\n")
} else if got is Result.Error(hive.net.SocketError.Closed(_)) {
return
} else if got is Result.Error(err) {
echo "dropped {hive.net.socketPeer(conn)}: {err.message}"
return
}
}
}
proc main(): void {
hive.net.socketServe(9000, handle)
}proc main(): void {
found := hive.net.resolve("db.internal")
if found is Result.Ok(addresses) {
for each address in addresses {
echo address
}
} else if found is Result.Error(hive.net.NetError.NotFound(_)) {
echo "nobody has registered db.internal"
} else if found is Result.Error(err) {
echo "could not look it up: {err.message}"
}
}