Slide 30 of 37

Networking: WebSockets

proc handle(conn: hive.net.WsConnection): void {
	if hive.net.wsReceive(conn) is Result.Ok(msg) {
		hive.net.wsSend(conn, "echo: {msg}")
	}
}

proc main(): void {
	hive.net.wsServe(8081, handle)
}
hive.net's WebSocket support is RFC 6455 end to end: the handshake, frame headers, masking, ping/pong and fragmentation are the runtime's business, and a program only ever sees whole messages as a Str. wsServe(port, handler) serves connections the same shape httpServe serves requests, calling a proc(WsConnection): void once per connection; wsConnect dials one as a client, and wsRequest reads back the HttpRequest that opened it. wsClose ends a connection from this side; a peer that hangs up on its own answers as "Closed" — the ordinary end of a conversation, not a failure to report.