WebSockets#

This protocol carries the messages over a websockets connection, for a client in a web browser.

Note

The JavaScript client implements this protocol, for a web page or Node.js.

Framing#

Each message is a Message, encoded according to the Protocol Buffers binary format and carried in one binary websockets message. The websockets message may be split across fragments.

Connecting#

A new install has a server for this protocol in the server window, at address 127.0.0.1 and port 50001. To add another, add a server and select Protobuf over WebSockets as its protocol.

Open a websockets connection to the server with the path /, for example ws://127.0.0.1:50001/. The upgrade request names no subprotocol. Then send the connection handshake. The upgrade and the connection_request together have 3 seconds to arrive, timed from the TCP connection.

The connection carries the requests, the responses and the stream updates. To end it, send a disconnect and then a close frame.

Web Pages#

A web page sends its origin with the upgrade request, and the server refuses a page whose origin it does not allow, with status 403. Origins, in the server window, lists the origins it allows:

  • localhost, the default, allows a page served from localhost or a loopback address, on any port, such as http://localhost:8000 or http://127.0.0.1:5173.

  • An origin, such as http://192.168.1.10:8000, allows pages from that scheme, host and port.

  • * allows any page, including one opened as a local file, which has the origin null.

The entries are comma-separated. A client that is not a web page, such as Node.js, sends no origin, and the server always accepts it.

Examples#

Note

These examples show the protocol, and omit much of the behavior a client library needs, such as handling errors and failed connections. A client library should implement the client specification in its entirety.

The examples run in Node.js, using the ws and protobufjs packages. A web browser provides the same WebSocket interface.

The following script connects to the server with the name “Example”, calls KRPC.GetStatus and prints the server version. It then ends the connection:

"use strict";

const WebSocket = require("ws");
const protobuf = require("protobufjs");

const root = protobuf.loadSync("krpc.proto");
const Message = root.lookupType("krpc.schema.Message");
const Tuple = root.lookupType("krpc.schema.Tuple");

function send(conn, message) {
  conn.send(Message.encode(Message.fromObject(message)).finish());
}

function receive(event) {
  const message = Message.decode(new Uint8Array(event.data));
  return Message.toObject(message, {
    enums: String,
    longs: Number,
    defaults: true,
  });
}

// Open a websockets connection to the server
const conn = new WebSocket("ws://127.0.0.1:50001/");
conn.binaryType = "arraybuffer";

conn.onopen = () => {
  // Send a connection request
  send(conn, {
    connectionRequest: { clientName: "Example", protocolVersion: 2 },
  });
};

conn.onmessage = (event) => {
  const message = receive(event);
  if (message.connectionResponse) {
    // Check the connection was successful
    const response = message.connectionResponse;
    if (response.status !== "OK")
      throw new Error(`Connection failed: ${response.message}`);
    if (response.protocolVersion !== 2)
      throw new Error("The server does not support protocol version 2");
    console.log("Connected to the server");

    // Invoke the KRPC.GetStatus RPC, in a request with the id 1
    send(conn, {
      request: {
        id: 1,
        calls: [{ service: "KRPC", procedure: "GetStatus" }],
      },
    });
  } else if (message.response) {
    // Check for an error in the response, and in the results
    const response = message.response;
    if (response.error)
      throw new Error(`ERROR: ${response.error.description}`);
    if (response.results[0].error)
      throw new Error(`ERROR: ${response.results[0].error.description}`);

    // Decode the return value, a ServerStatus structure sent as a Tuple of
    // its fields, and print out the server version, the first field
    const status = Tuple.decode(response.results[0].value);
    console.log(protobuf.Reader.create(status.items[0]).string());

    // End the connection with a disconnect, then a close frame
    send(conn, { disconnect: { reason: "CLOSED" } });
    conn.close();
  }
};

The following script adds a stream, then receives its updates on the same connection:

"use strict";

const WebSocket = require("ws");
const protobuf = require("protobufjs");

const root = protobuf.loadSync("krpc.proto");
const Message = root.lookupType("krpc.schema.Message");
const ProcedureCall = root.lookupType("krpc.schema.ProcedureCall");
const Tuple = root.lookupType("krpc.schema.Tuple");

function send(conn, message) {
  conn.send(Message.encode(Message.fromObject(message)).finish());
}

function receive(event) {
  const message = Message.decode(new Uint8Array(event.data));
  return Message.toObject(message, {
    enums: String,
    longs: Number,
    defaults: true,
  });
}

// Open a websockets connection to the server
const conn = new WebSocket("ws://127.0.0.1:50001/");
conn.binaryType = "arraybuffer";

conn.onopen = () => {
  // Send a connection request
  send(conn, {
    connectionRequest: { clientName: "Example", protocolVersion: 2 },
  });
};

let streamId = null;

conn.onmessage = (event) => {
  const message = receive(event);
  if (message.connectionResponse) {
    // Check the connection was successful
    const response = message.connectionResponse;
    if (response.status !== "OK")
      throw new Error(`Connection failed: ${response.message}`);
    if (response.protocolVersion !== 2)
      throw new Error("The server does not support protocol version 2");
    console.log("Connected to the server");

    // Build a KRPC.GetStatus call to be streamed
    const streamCall = ProcedureCall.encode({
      service: "KRPC",
      procedure: "GetStatus",
    }).finish();

    // Call KRPC.AddStream to add the stream, in a request with the id 1
    const call = {
      service: "KRPC",
      procedure: "AddStream",
      arguments: [{ position: 0, value: streamCall }],
    };
    send(conn, { request: { id: 1, calls: [call] } });
  } else if (message.response) {
    // Check for an error in the response, and in the results
    const response = message.response;
    if (response.error)
      throw new Error(`ERROR: ${response.error.description}`);
    if (response.results[0].error)
      throw new Error(`ERROR: ${response.results[0].error.description}`);

    // Decode the return value, which is the stream id as a uint64. The
    // stream's first update follows it.
    const id = protobuf.Reader.create(response.results[0].value).uint64();
    streamId = protobuf.util.longToNumber(id, true);
  } else if (message.streamUpdate) {
    // Decode and print the return value of each stream update
    for (const result of message.streamUpdate.results) {
      if (result.id === streamId) {
        // The value is a ServerStatus structure sent as a Tuple of its
        // fields. Its fourth field is the server statistics, another
        // structure, whose second field is the number of bytes the server
        // has written.
        const status = Tuple.decode(result.result.value);
        const statistics = Tuple.decode(status.items[3]);
        console.log(
          protobuf.Reader.create(statistics.items[1]).uint64().toString(),
        );
      }
    }
  }
};