The standard librarySlide 68 of 86
68wsThe standard library

WebSockets

WebSockets follow RFC 6455, and the runtime handles all of it (the handshake, framing, masking, ping and pong, and fragmentation), so a program only sees whole messages, as Str.

  • wsServe(port, handler) calls a proc(WsConnection): void once per connection, each on its own thread. The connection closes when the handler returns, so a handler that exchanges more than one message loops.
  • wsConnect(url) connects as a client and answers with a Result.
  • wsReceive(conn) waits for the next message; wsSend(conn, message) answers with the number of bytes it sent; wsClose(conn) closes the connection from this side.
  • wsRequest(conn) is the HttpRequest that opened the connection, as a plain value.
  • conn.address is the far end, as "host:port". It is a field; everything else about a connection is a call.
  • httpWsServe(port, handler, wsHandler) serves HTTP and WebSockets on one port. Every request reaches handler, an httpServe handler, and answering one with 101 hands it to wsHandler.

A hive.net.WsError is Handshake, Protocol, Closed, Send or Receive, each with a message. A peer hanging up gives WsError.Closed: the normal end of a conversation, not a failure to report.

proc handle(conn: hive.net.WsConnection): void {
	// The connection lasts as long as the handler does, so it loops
	// until the other side hangs up.
	mut open := true
	for ; open; {
		got := hive.net.wsReceive(conn)
		if got is Result.Ok(msg) {
			hive.net.wsSend(conn, "echo: {msg}")
		} else {
			open = false
		}
	}
}

proc main(): void {
	hive.net.wsServe(8081, handle)
}
HTTP and WebSockets on one port
proc route(req: hive.net.HttpRequest): hive.net.HttpResponse {
	if req.url == "/feed" {
		// Answering 101 hands this request to the WebSocket handler.
		return hive.net.HttpResponse(101, [], "")
	}
	return hive.net.HttpResponse(200, [], "a page")
}

proc feed(conn: hive.net.WsConnection): void {
	// The far end, as "host:port".
	hive.net.wsSend(conn, "hello, {conn.address}")
}

proc main(): void {
	hive.net.httpWsServe(8080, route, feed)
}