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 aproc(WsConnection): voidonce 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 aResult.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 theHttpRequestthat opened the connection, as a plain value.conn.addressis 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 reacheshandler, anhttpServehandler, and answering one with101hands it towsHandler.
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)
}