ws module

WebSocket protocol on top of a raw connection. Designed to pair with web.upgrade(req) — the web server hands you a raw conn after the HTTP upgrade, and ws turns it into a frame-oriented socket.

import "web" as web;
import "ws"  as ws;

var app = web.app();
app.get("/chat", function (req) {
    if (not ws.validate_request(req)) { return web.error(400, "bad ws req"); }

    var conn = web.upgrade(req);
    var sock = ws.accept(conn, req);

    sock.on_message(function (msg)  { sock.send("echo: " + msg); });
    sock.on_close  (function (code) { print("closed:", code); });
});

app.listen({ port: 3000 });

API

FunctionDescription
ws.validate_request(req) → boolTrue if req is a valid WebSocket upgrade request.
ws.accept(conn, req) → sockSend the upgrade response and return a frame-oriented socket.

Socket object

MethodDescription
sock.on_message(fn)fn(text) per text frame.
sock.on_binary(fn)fn(bytes) per binary frame.
sock.on_close(fn)fn(code) when the peer disconnects.
sock.send(text)Send a text frame.
sock.send_binary(bytes)Send a binary frame.
sock.close(code?)Close with an optional status code.

See also

  • webweb.upgrade(req) returns the raw connection.