Grav v1.14.0

WebSocket

import "std/net" (not included in import "std") · namespace std.net

WebSockets (RFC 6455): long-lived, two-way connections over HTTP, used for chat, live updates and games. WebSocket.route(server, path, handler) serves them from an HttpServer, on the same port as its HTTP routes; WebSocket.connect(url) opens a client connection.

grav
import "std"
import "std/net"

fn main() {
    let app = new HttpServer()
    WebSocket.route(app, "/echo", fn(ws: WebSocket) {
        ws.messages(fn(m: WsMessage) {
            if (m.text() == "bye") { ws.close(4000, "see you") }
            else { ws.send("echo: " + m.text()) }
        })
    })
    app.start(0)

    let ws = WebSocket.connect("ws://127.0.0.1:${app.port()}/echo")
    ws.send("hello")
    print(ws.receive().text())
    ws.send("bye")
    print("closed: ${ws.receive() == null}, code ${ws.closeCode}, reason: ${ws.closeReason}")
    app.stop()
}
Output
echo: hello
closed: true, code 4000, reason: see you
  • receive() returns the next WsMessage (text(), data as Bytes, isText(), isBinary()), or null once the connection is closed. messages(f) calls f for each message until then.
  • send(text) sends a text frame, sendBytes(data) a binary one; send may be called from several threads at once.
  • Pings are answered automatically; ping() checks that the other side is alive. Fragmented messages are reassembled; maxMessageBytes limits their size.
  • close(code, reason) performs the closing handshake; closeCode and closeReason hold what the other side sent.
  • wss:// URLs use TLS; WebSocket.connect(url, timeoutMs, ctx) takes a TlsContext for servers the system does not trust, and a server started with HttpServer.startTls serves wss:// on its routes.

API

class WsMessage

One complete message.

Constructors

  • new WsMessage(binary: bool, data: Bytes)

Fields

  • binary: bool — Whether the message was sent as binary (else text).
  • data: Bytes — The payload.

Methods

  • fn isText() -> bool — Whether this is a text message.
  • fn isBinary() -> bool — Whether this is a binary message.
  • fn text() -> string — The message as text.
  • fn toString() -> string — "WsMessage(text)" or "WsMessage(n bytes)".

class WebSocket

A WebSocket connection (either end).

Constructors

  • new WebSocket(conn: TcpStream, client: bool, path: string)

Static members

  • static fn connect(url: string) -> WebSocket — Connect to "ws://host[:port]/path" or "wss://..." (TLS, verified against the system's CAs). Throws NetError if the server refuses.
  • static fn connect(url: string, timeoutMs: int) -> WebSocket — Opens a WebSocket to url (ws:// or wss://), waiting at most timeoutMs (NetError on failure).
  • static fn connect(url: string, timeoutMs: int, tls: TlsContext) -> WebSocket — Opens a WebSocket; for wss://, tls says which servers to trust (null: the system's CAs).
  • static fn accept(req: HttpRequest, conn: TcpStream) -> WebSocket — Complete the server side of the handshake for an upgrade request.
  • static fn route(server: HttpServer, path: string, handler: fn(WebSocket)) — Serve WebSockets on path of an HttpServer: handler runs on the connection's thread; the socket is closed when it returns.

Fields

  • closeCode: int — The close code the peer sent (1000 = normal), or 0.
  • closeReason: string — The reason text the peer sent with its close, or "".
  • maxMessageBytes: int — Messages larger than this (bytes) close the connection with 1009.
  • path: string — The request path (server side) or URL (client side).

Methods

  • fn send(text: string) — Sends a text message.
  • fn sendBytes(data: Bytes) — Sends a binary message.
  • fn ping() — Sends a ping frame.
  • fn isOpen() -> bool — Whether the connection is open.
  • fn receive() -> WsMessage — The next message, or null once the connection has closed.
  • fn messages(f: fn(WsMessage)) — Calls f with each message until the connection closes.
  • fn close() — Closes the connection normally (status 1000).
  • fn close(code: int, reason: string) — Send a close frame with a status code and reason, then close the socket.

Edit this page on GitHub