Java#

This guide describes how to install the Java client, and the features it provides. The Client API Reference describes each class and method.

Installing the Library#

The library is the krpc.client package, published to Maven Central as io.github.krpc:krpc-java. It requires Java 17 or later.

To add it to a Gradle project, in build.gradle.kts:

dependencies {
    implementation("io.github.krpc:krpc-java:0.8.0")
}

To add it to a Maven project, in pom.xml:

<dependency>
  <groupId>io.github.krpc</groupId>
  <artifactId>krpc-java</artifactId>
  <version>0.8.0</version>
</dependency>

Gradle and Maven also fetch the library’s dependencies, protobuf and javatuples.

Without a build tool, download the jar from GitHub, along with the jars of its two dependencies at the versions its Maven Central page lists. To compile a program with javac, add the three jars to the class path:

javac -cp krpc-java.jar:protobuf-java.jar:javatuples.jar Example.java

The paths are those of the jars on your machine.

Connecting to the Server#

The game must be running with the server started. The Server Plugin in the getting started guide shows how to install and start it.

The client connects over TCP/IP or over a local socket. Each server in the server window uses one protocol, and accepts connections over that protocol only. Pick the protocol when you add the server, and connect with the matching method.

Note

A server with “Auto-accept new clients” turned off answers only once the player approves the connection in game. The connection fails after 5 seconds by default. Pass a longer handshakeTimeout, such as Duration.ofMinutes(5), to give the player time to approve it.

Over TCP/IP#

Select “Protobuf over TCP/IP” as the server’s protocol. newInstance connects to it, and returns a Connection. You make every call through this object. The following connects to a server with the default settings, address 127.0.0.1 and port 50000, and prints its version:

import krpc.client.Connection;
import krpc.client.services.KRPC;


public class Connecting1 {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      System.out.println(
          KRPC.newInstance(connection).getStatus().getVersion());
    }
  }
}

newInstance also takes a name for the connection, then the address and port of the server. These match the address and port shown in the server window. The name appears in the server window in the game:

import krpc.client.Connection;
import krpc.client.services.KRPC;


public class Connecting2 {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance(
             "My Example Program", "192.168.1.10", 1000)) {
      System.out.println(
          KRPC.newInstance(connection).getStatus().getVersion());
    }
  }
}

TCP/IP works over a network, so your program can run on a different machine from the game.

Over a Local Socket#

Select “Protobuf over local socket” as the server’s protocol. newLocalInstance connects to it, and returns a Connection as newInstance does. The following connects to a server with the default settings, at the default socket path for your platform, and prints its version:

import krpc.client.Connection;
import krpc.client.services.KRPC;


public class ConnectingLocal {
  public static void main(String[] args) {
    try (Connection connection =
             Connection.newLocalInstance("My Example Program")) {
      System.out.println(
          KRPC.newInstance(connection).getStatus().getVersion());
    }
  }
}

newLocalInstance also takes a path after the name, for a server with another socket path. The path matches the one shown in the server window.

A local socket works only on the machine running the game. It has lower overhead than TCP/IP, so it is faster.

Closing the Connection#

A Connection is AutoCloseable. Open it in a try-with-resources statement, as the examples in this guide do, to close it at the end of the block. close closes a connection explicitly:

import krpc.client.Connection;
import krpc.client.services.KRPC;


public class Connecting3 {
  public static void main(String[] args) {
    Connection connection = Connection.newInstance("My Example Program");
    System.out.println(
        KRPC.newInstance(connection).getStatus().getVersion());
    connection.close();
  }
}

A connection you do not close stays open until your program exits, even when your program no longer holds it.

Calling Remote Procedures#

The server provides procedures for your program to call, grouped into services.

The following gets the active vessel from getActiveVessel, an object of type Vessel. It sets the vessel’s name, then prints its altitude:

import krpc.client.Connection;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
import krpc.client.services.SpaceCenter.Vessel;


public class RemoteProcedures {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Vessel vessel = spaceCenter.getActiveVessel();

      vessel.setName("My Vessel");

      Flight flightInfo = vessel.flight(null);
      System.out.println(flightInfo.getMeanAltitude());
    }
  }
}

Each service is a class in the krpc.client.services package, such as SpaceCenter. Its static newInstance method takes the connection, and returns an object for the service. A property is a pair of methods, such as getName and setName.

Handling Errors#

A procedure that fails on the server throws an exception in your program. The following catches the error from loading a save that does not exist:

import krpc.client.Connection;
import krpc.client.services.SpaceCenter;


public class Errors {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      try {
        spaceCenter.load("missing");
      } catch (IllegalArgumentException exn) {
        System.out.println("Failed to load the save: " + exn.getMessage());
      }
    }
  }
}

The exception you catch depends on the error:

Every exception is unchecked. Every exception of the client’s own derives RemoteException, and a standard Java exception does not.

Values#

Procedures take and return Java values, such as int, String, java.util.List and Map, and null for a null. A tuple is a tuple of org.javatuples, such as Pair. The services also define their own types:

  • A class is a remote object, described below.

  • A structure is a class with a getter for each field.

  • An enumeration is an enum, or a class of constants for a flags enumeration.

Flags Enumerations#

A flags enumeration, such as MapFilterType, holds any combination of its values. It is a class of constants, which you combine with or and test for one with contains:

import krpc.client.Connection;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.MapFilterType;


public class Flags {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);

      // Show only probes and ships in map mode
      spaceCenter.setMapFilter(
          MapFilterType.PROBES.or(MapFilterType.SHIPS));

      // Check whether map mode shows debris
      MapFilterType filter = spaceCenter.getMapFilter();
      System.out.println(filter.contains(MapFilterType.DEBRIS));

      // Show debris as well
      spaceCenter.setMapFilter(filter.or(MapFilterType.DEBRIS));
    }
  }
}

and, xor and andNot give the other combinations of two values.

Remote Objects#

Many procedures return an object identifying something in the game, such as a vessel or a part. The object holds no copy of the game’s state. It is just a reference to it. Each call through it reads the game as it is now:

import krpc.client.Connection;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
import krpc.client.services.SpaceCenter.Vessel;


public class RemoteObjects {
  public static void main(String[] args) throws InterruptedException {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Vessel vessel = spaceCenter.getActiveVessel();
      Flight flightInfo = vessel.flight(null);

      // Each read gets the current altitude from the game
      System.out.println(flightInfo.getMeanAltitude());
      Thread.sleep(1000);
      System.out.println(flightInfo.getMeanAltitude());

      // Two objects for the same vessel are equal
      System.out.println(vessel.equals(spaceCenter.getActiveVessel()));
    }
  }
}

Two objects for the same thing in the game are equal, and have the same hashCode. They can be used as the keys of a HashMap. Remote objects are also Comparable, so they can be sorted and used as the keys of a TreeMap.

Once the thing an object identifies is destroyed, such as a part that explodes, each call through it throws ObjectDestroyedException.

An object for a vessel or a part keeps working when you load a save, quickload or revert, and then reads the loaded game. Other objects depend on what they identify. A maneuver node, for example, is destroyed by a load.

A vessel far from the active vessel is unloaded, and the game keeps no parts for it. The vessel itself reads normally, but a call on one of its parts throws ObjectNotLoadedException. The part works again once the vessel comes back into range.

See also

Object Lifetime describes how each kind of object behaves in more detail.

Calling Methods#

You call a method on an object of its class. A static method needs no object, and you call it on the class itself, passing the connection as its first argument. addStream streams it with the class, the method’s name and its other arguments, as the stream runs on the connection it is added on:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Orbit;
import krpc.client.services.SpaceCenter.ReferenceFrame;
import krpc.client.services.SpaceCenter.Vessel;

import org.javatuples.Triplet;


public class StaticMethods {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      Vessel vessel = SpaceCenter.newInstance(connection).getActiveVessel();
      ReferenceFrame frame =
          vessel.getOrbit().getBody().getReferenceFrame();

      // Call a method on an object
      System.out.println(vessel.position(frame));

      // Call a static method, passing the connection first
      System.out.println(Orbit.referencePlaneDirection(connection, frame));

      // Stream it, with only its other arguments
      Stream<Triplet<Double, Double, Double>> direction =
          connection.addStream(
              Orbit.class, "referencePlaneDirection", frame);
      System.out.println(direction.get());
    }
  }
}

bind binds a class’s static methods to a connection, so each call leaves it out:

import krpc.client.Connection;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Orbit;
import krpc.client.services.SpaceCenter.ReferenceFrame;


public class BoundStaticMethods {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      ReferenceFrame frame = SpaceCenter.newInstance(connection)
          .getActiveVessel().getReferenceFrame();

      // Bind the static methods to the connection once
      Orbit.Bound orbit = Orbit.bind(connection);
      System.out.println(orbit.referencePlaneNormal(frame));
      System.out.println(orbit.referencePlaneDirection(frame));
    }
  }
}

Streaming Data#

A common use of kRPC is to read data from the game continuously. The following does so by calling a remote procedure in a loop, printing the position of the active vessel:

import krpc.client.Connection;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.ReferenceFrame;
import krpc.client.services.SpaceCenter.Vessel;


public class Streaming1 {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Vessel vessel = spaceCenter.getActiveVessel();
      ReferenceFrame refframe =
          vessel.getOrbit().getBody().getReferenceFrame();
      while (true) {
        System.out.println(vessel.position(refframe));
      }
    }
  }
}

Each call sends a request to the server and waits for its response. A stream is more efficient. The server runs the call repeatedly, and sends your program the result each time it changes.

The following does the same as above using a stream:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.ReferenceFrame;
import krpc.client.services.SpaceCenter.Vessel;

import org.javatuples.Triplet;


public class Streaming2 {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Vessel vessel = spaceCenter.getActiveVessel();
      ReferenceFrame refframe =
          vessel.getOrbit().getBody().getReferenceFrame();
      Stream<Triplet<Double, Double, Double>> position =
          connection.addStream(vessel, "position", refframe);
      while (true) {
        System.out.println(position.get());
      }
    }
  }
}

addStream creates the stream from a remote object, the name of a method, and its arguments. It returns a Stream, whose type parameter is the type of the method’s value. get returns the stream’s latest value.

A property is streamed with the name of its getter:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;


public class Streaming3 {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Flight flightInfo = spaceCenter.getActiveVessel().flight(null);
      Stream<Double> altitude =
          connection.addStream(flightInfo, "getMeanAltitude");
      while (true) {
        System.out.println(altitude.get());
      }
    }
  }
}

A procedure of a service is streamed with the service’s class in place of an object, such as connection.addStream(SpaceCenter.class, "getUT").

Each call to addStream creates another stream. A stream of a procedure with no return value runs the call on each update for its effects. Its value is null, as a Stream<Void>.

A stream runs until you remove it with remove, or the connection closes. It keeps running after your program drops its last reference to it, so remove a stream you no longer need. A try-with-resources statement removes a stream at the end of the block:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;


public class StreamScope {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Flight flight = spaceCenter.getActiveVessel().flight(null);
      try (Stream<Double> altitude =
               connection.addStream(flight, "getMeanAltitude")) {
        for (int i = 0; i < 10; i++) {
          System.out.println(altitude.get());
        }
      }
      // The stream was removed at the end of the block
    }
  }
}

By default, the server sends a stream’s value each time it changes. Call setRate to limit how many times a second the stream updates:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;


public class StreamRate {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Flight flightInfo = spaceCenter.getActiveVessel().flight(null);
      Stream<Double> altitude =
          connection.addStream(flightInfo, "getMeanAltitude");
      // Update the stream at most 10 times a second
      altitude.setRate(10);
    }
  }
}

Waiting for Changes#

Each stream has a condition variable, the object getCondition returns. waitForUpdate blocks until the stream’s value changes. The following waits for the abort button to be pressed:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Control;


public class ConditionVariables {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Control control = spaceCenter.getActiveVessel().getControl();
      Stream<Boolean> abort = connection.addStream(control, "getAbort");
      synchronized (abort.getCondition()) {
        while (!abort.get()) {
          abort.waitForUpdate();
        }
      }
    }
  }
}

Hold the condition when you call waitForUpdate, as the synchronized block does here. While you hold it, the value changes only when you wait, so the loop misses no updates. An ending reaches you the same way: the wait returns, and your next read or wait throws the exception that ended the stream.

waitForUpdateWithTimeout takes a timeout in seconds, and returns false when it elapses before an update.

Callbacks#

A callback is a function the client calls with each new value of a stream. The following adds two callbacks to a stream of the abort button:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Control;


public class Callbacks {
  public static void main(String[] args) throws InterruptedException {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Control control = spaceCenter.getActiveVessel().getControl();
      Stream<Boolean> abort = connection.addStream(control, "getAbort");
      abort.addCallback(
          x -> System.out.println("Abort 1 called with a value of " + x));
      abort.addCallback(
          x -> System.out.println("Abort 2 called with a value of " + x));

      // Keep the program running, while the callbacks are called
      while (true) {
        Thread.sleep(1000);
      }
    }
  }
}

addCallback returns a tag, which removeCallback takes to remove the callback.

A callback added to a stream that already has a value is called with that value straight away. It is then called with each new value, in order.

Note

Each connection has a callback thread, which runs the callbacks of its streams one at a time. A callback can make remote procedure calls. Other callbacks and waits are held up while it runs, so return promptly, and do not wait on a stream in a callback. For a long running task, start a worker thread from the callback.

Stream Endings#

A stream ends when its procedure throws an exception, when the server removes it, when you remove it, or when the connection closes. Getting the stream’s value or waiting on it then throws the exception that ended it. The following streams the temperature of a part until the part is destroyed:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.KRPC;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Part;


public class StreamEnd {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Part part = spaceCenter.getActiveVessel().getParts().getRoot();
      Stream<Double> temperature =
          connection.addStream(part, "getTemperature");
      try {
        synchronized (temperature.getCondition()) {
          while (true) {
            temperature.waitForUpdate();
            System.out.println("Temperature " + temperature.get());
          }
        }
      } catch (KRPC.ObjectDestroyedException exn) {
        System.out.println("The part was destroyed");
      }
    }
  }
}

The exception is the one the procedure threw, or one of the following:

An exception for an object that is not loaded, or for a procedure not available in the current game scene, does not end the stream. It pauses the stream’s updates, and the stream keeps its last value. The updates resume once the object or the scene is available.

See also

Object Lifetime describes when each kind of object is not loaded, and how streams behave around a load.

addEndCallback adds a callback that is called once when the stream ends, with the exception. The following prints the temperature of a part with a callback, and prints the exception when the stream ends:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Part;


public class EndCallback {
  public static void main(String[] args) throws InterruptedException {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Part part = spaceCenter.getActiveVessel().getParts().getRoot();
      Stream<Double> temperature =
          connection.addStream(part, "getTemperature");
      temperature.addCallback(
          value -> System.out.println("Temperature " + value));
      temperature.addEndCallback(exn -> System.out.println(
          "The stream ended: " + exn.getMessage()));

      // Keep the program running, while the callbacks are called
      while (true) {
        Thread.sleep(1000);
      }
    }
  }
}

Server Side Functions#

A server side function runs inside the game. You build it in your program with the expression API, and the client sends it to the server. The following reads the vessel’s altitude and speed together:

import java.util.Arrays;
import krpc.client.Connection;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
import krpc.client.services.SpaceCenter.Vessel;
import krpc.schema.KRPC.ProcedureCall;
import org.javatuples.Pair;

public class RunFunction {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      Vessel vessel = SpaceCenter.newInstance(connection).getActiveVessel();
      Flight flight =
          vessel.flight(vessel.getOrbit().getBody().getReferenceFrame());

      // Get the remote procedure calls as message objects,
      // so they can be passed to the server
      ProcedureCall meanAltitude =
          connection.getCall(flight, "getMeanAltitude");
      ProcedureCall speed = connection.getCall(flight, "getSpeed");

      // Build a function that reads the altitude and the speed
      Expression.Bound e = Expression.bind(connection);
      Expression expr = e.createTuple(
          Arrays.asList(e.call(meanAltitude), e.call(speed)));

      // Run once, so both values come from the same physics tick
      Pair<Double, Double> result = connection.run(expr);
      System.out.println("Altitude: " + result.getValue0()
          + " m, speed: " + result.getValue1() + " m/s");
    }
  }
}

getCall turns a call into a message, and the static methods of Expression build the function from it. getCallTemplate names a procedure through its class, with no object or arguments, for Expression.callWithArguments to supply each argument, as in Functions and Collections. The Expression API in the server side functions guide describes these methods, and shows how to build larger functions.

Running a Function#

run runs a function once, and returns its value. The server runs the whole function within one physics tick, so every value it reads comes from the same moment in the game. In the example, the altitude and the speed are consistent with each other, which two separate calls cannot guarantee.

Streaming a Function#

Pass a function to addStream to stream its value. The server evaluates the function on each update, within one physics tick. The following streams the vessel’s altitude in kilometers:

import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;

public class FunctionStream {
  public static void main(String[] args) throws InterruptedException {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Flight flight = spaceCenter.getActiveVessel().flight(null);

      // Build a function that computes
      // the vessel's altitude in kilometers
      Expression.Bound e = Expression.bind(connection);
      Expression expr = e.divide(
          e.call(connection.getCall(flight, "getMeanAltitude")),
          e.constantDouble(1000));

      // Stream the value of the function
      Stream<Double> stream = connection.addStream(expr);
      while (true) {
        System.out.println("Altitude: " + stream.get() + " km");
        Thread.sleep(1000);
      }
    }
  }
}

The stream’s type parameter must hold the function’s value. Otherwise assigning a value throws a ClassCastException.

A function stream ends on an exception its function throws, just like an ordinary stream. Unlike an ordinary stream, it also ends on ObjectNotLoadedException, thrown while the game loads or when a vessel unloads. The server cannot pause a function partway through, and running it again would repeat its effects. To keep a function running through a load, catch the exception in the function:

Expression.Bound e = Expression.bind(connection);
// altitude = meanAltitude / 1000, or 0 if the vessel is not loaded
Expression altitude =
    e.variable("altitude", Type.bind(connection).double_());
Expression km = e.divide(
    e.call(connection.getCall(flight, "getMeanAltitude")),
    e.constantDouble(1000));
Expression altitudeKm = e.blockWithVariables(
    Arrays.asList(altitude),
    Arrays.asList(
        e.tryCatch(
            e.assign(altitude, km),
            "KRPC", "ObjectNotLoadedException", null,
            e.assign(altitude, e.constantDouble(0))),
        altitude));

Stream<Double> stream = connection.addStream(altitudeKm);

Events#

A common use of kRPC is to wait for something to happen in the game, such as the vessel reaching an altitude. An event does this efficiently. The server checks a condition, written as a server side function, and sends your program an update when it becomes true. The following waits until the vessel’s altitude exceeds 1000 meters:

import krpc.client.Connection;
import krpc.client.Event;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
import krpc.schema.KRPC.ProcedureCall;


public class CustomEvent {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Flight flight = spaceCenter.getActiveVessel().flight(null);

      // Get the remote procedure call as a message object,
      // so it can be passed to the server
      ProcedureCall meanAltitude =
          connection.getCall(flight, "getMeanAltitude");

      // Build the function on the server
      Expression.Bound e = Expression.bind(connection);
      Expression expr = e.greaterThan(
          e.call(meanAltitude), e.constantDouble(1000));

      Event event = connection.addEvent(expr);
      synchronized (event.getCondition()) {
        event.waitFor();
        System.out.println("Altitude reached 1000m");
      }
    }
  }
}

addEvent creates the event, and waitFor waits for it to fire. The server checks the condition every physics tick, so the event catches a condition that holds for only a moment, which a loop of calls can miss.

The event fires again each time the condition becomes true after being false. Call remove to stop it. A try-with-resources statement removes an event at the end of the block:

import krpc.client.Connection;
import krpc.client.Event;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;


public class EventScope {
  public static void main(String[] args) {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Flight flight = spaceCenter.getActiveVessel().flight(null);
      Expression.Bound e = Expression.bind(connection);
      Expression expr = e.greaterThan(
          e.call(connection.getCall(flight, "getMeanAltitude")),
          e.constantDouble(1000));
      try (Event event = connection.addEvent(expr)) {
        synchronized (event.getCondition()) {
          event.waitFor();
          System.out.println("Altitude reached 1000m");
        }
      }
      // The event was removed at the end of the block
    }
  }
}

As with a stream, hold the event’s condition when you call waitFor. A wait returns straight away if the event has fired since your last wait, so a firing between two waits is not missed.

Event Callbacks#

An event can also call a callback each time it fires. The callback is a Runnable:

import krpc.client.Connection;
import krpc.client.Event;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;


public class EventCallback {
  public static void main(String[] args) throws InterruptedException {
    try (Connection connection = Connection.newInstance()) {
      SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
      Flight flight = spaceCenter.getActiveVessel().flight(null);

      Expression.Bound e = Expression.bind(connection);
      Expression expr = e.greaterThan(
          e.call(connection.getCall(flight, "getMeanAltitude")),
          e.constantDouble(1000));
      Event event = connection.addEvent(expr);

      event.addCallback(() -> System.out.println("Altitude reached 1000m"));

      // Keep the program running, while the callback is called
      while (true) {
        Thread.sleep(1000);
      }
    }
  }
}

Callbacks for events run on the connection’s callback thread, as the callbacks of a stream do.

Event Endings#

An event ends in the same ways as a stream. Waiting on an event that has ended throws the exception that ended it.

When the event fires just before the server ends it, your next wait returns for that firing first. Removing the event or closing the connection ends it at once.

addEndCallback adds a callback that is called once when the event ends, with the exception, just like an ordinary stream.

Threading#

A connection can be shared between threads. Each thread makes calls over it as it would alone, and each call returns its own result. The following prints the altitude and speed of the vessel from two threads:

import krpc.client.Connection;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
import krpc.client.services.SpaceCenter.Vessel;


public class Threads {
  public static void main(String[] args) throws InterruptedException {
    try (Connection connection = Connection.newInstance()) {
      Vessel vessel = SpaceCenter.newInstance(connection).getActiveVessel();
      Flight flightInfo =
          vessel.flight(vessel.getOrbit().getBody().getReferenceFrame());

      // Both threads make calls over the same connection
      Thread altitude = new Thread(() -> {
        for (int i = 0; i < 10; i++) {
          System.out.println("Altitude: " + flightInfo.getMeanAltitude());
        }
      });
      Thread speed = new Thread(() -> {
        for (int i = 0; i < 10; i++) {
          System.out.println("Speed: " + flightInfo.getSpeed());
        }
      });
      altitude.start();
      speed.start();
      altitude.join();
      speed.join();
    }
  }
}

Streams and events can also be used from any thread:

  • Several threads can read a stream, or wait on a stream or an event. A change wakes every thread waiting for it.

  • A thread holding a stream’s condition does not stop other threads from making calls.

  • Callbacks run on the connection’s callback thread, one at a time, and never on your program’s threads. A callback added to a stream that already has a value is different. Its first call, with that value, might run on your thread, before addCallback returns. Protect state that a callback shares with your program’s threads, such as with a synchronized block.

A wait on a stream or an event that another thread removes throws a StreamException. Interrupting a waiting thread ends its wait with a CancellationException, and the stream or event runs on.

Deprecated Members#

A member of a service can be deprecated, when a newer member replaces it. A deprecated member still works, but may be removed in a future release, so move to its replacement.

The API reference and the member’s documentation comment mark it as deprecated, and name the replacement. The member carries the @Deprecated annotation, so javac prints a note when a program uses it. Compile with -Xlint:deprecation to list each use.

Service Stubs#

The client includes code for each service that ships with kRPC, generated from the services of one kRPC release and compiled into the client’s jar. These stubs are the classes in the krpc.client.services package, such as SpaceCenter.

The stubs match the server from the same release, so install the client version that matches your server. With another version, a procedure that was removed or renamed throws an exception when you call it. A parameter or return type that changed is not checked, so a call can send or return a wrong value with no error.

A service with no stub, such as one added by another mod, needs stubs of its own. Generating Service Code for Static Clients shows how to generate them.

Client API Reference#

class Connection#

A connection to the server. Obtain one by calling newInstance or newLocalInstance. It is AutoCloseable, so a try-with-resources statement closes it at the end of the block.

static Connection newInstance()#
static Connection newInstance(String name)#
static Connection newInstance(String name, String address)#
static Connection newInstance(String name, String address, int port)#
static Connection newInstance(String name, String address, int port, java.time.Duration timeout)#
static Connection newInstance(String name, String address, int port, java.time.Duration timeout, java.time.Duration handshakeTimeout)#
static Connection newInstance(String name, String address, int port, java.time.Duration timeout, java.time.Duration handshakeTimeout, java.time.Duration stallTimeout)#
static Connection newInstance(String name, java.net.InetAddress address)#
static Connection newInstance(String name, java.net.InetAddress address, int port)#
static Connection newInstance(String name, java.net.InetAddress address, int port, java.time.Duration timeout)#
static Connection newInstance(String name, java.net.InetAddress address, int port, java.time.Duration timeout, java.time.Duration handshakeTimeout)#
static Connection newInstance(String name, java.net.InetAddress address, int port, java.time.Duration timeout, java.time.Duration handshakeTimeout, java.time.Duration stallTimeout)#

Connects to a kRPC server over TCP/IP.

Parameters:
  • name (String) – A name for the connection, shown in the server window in the game.

  • address (String) – The address of the server, as a host name, an IP address, or a InetAddress. Defaults to 127.0.0.1.

  • port (int) – The port of the server. Defaults to 50000.

  • timeout (java.time.Duration) – How long to wait for the connection to open. Defaults to zero, which waits indefinitely. Without a timeout, a network that drops the connection attempt leaves the client waiting.

  • handshakeTimeout (java.time.Duration) – How long to wait for the server to accept the connection. Defaults to 5 seconds.

  • stallTimeout (java.time.Duration) – How long a message from the server can go without a new byte, once it has started to arrive, before the connection fails. Defaults to 30 seconds.

Throws a ConnectionException if the connection fails or the server refuses it, and an IllegalArgumentException for a negative timeout, or a handshake or stall timeout of zero.

static Connection newLocalInstance()#
static Connection newLocalInstance(String name)#
static Connection newLocalInstance(String name, String path)#
static Connection newLocalInstance(String name, String path, java.time.Duration handshakeTimeout)#
static Connection newLocalInstance(String name, String path, java.time.Duration handshakeTimeout, java.time.Duration stallTimeout)#

Connects to a kRPC server on the same machine over a local socket. The server must use the local socket protocol.

Local sockets are available on Linux, macOS, and Windows 10 1803 and Windows Server 2019 or later.

Parameters:
  • name (String) – A name for the connection, shown in the server window in the game.

  • path (String) – The path of the server’s socket, shown in the server window in the game. Defaults to the path the server uses unless it was configured with another.

  • handshakeTimeout (java.time.Duration) – As for newInstance.

  • stallTimeout (java.time.Duration) – As for newInstance.

Throws a ConnectionException and an IllegalArgumentException as newInstance does.

void close()#

Closes the connection. Closing a connection that is already closed does nothing.

<T> Stream<T> addStream(RemoteObject instance, String method, Object... args)#

Creates a stream for a call to the method named method of the remote object instance, with arguments args, and returns a Stream. Each call creates a new stream. Stream a property by passing the name of its getter.

Throws an IllegalArgumentException if the object has no method of that name taking the arguments.

<T> Stream<T> addStream(Class<?> clazz, String method, Object... args)#

Creates a stream for a call to the method named method of the class clazz, with arguments args, and returns a Stream. The class is a service, such as SpaceCenter.class, a class with a static method, or its Bound class. The call runs on this connection, so the arguments of a static method leave out its connection. Each call creates a new stream.

Throws an IllegalArgumentException if the class has no method of that name taking the arguments.

Note

Passing the connection first, for a static method, is deprecated. The call runs on this connection, whichever connection is passed.

<T> Stream<T> addStream(KRPC.Expression function)#

Creates a stream from a server side function, evaluated on each update, and returns a Stream. Each call creates a new stream. The type parameter must hold the function’s value, or assigning a value throws a ClassCastException.

A function with no value runs on each update for its effects, and the stream’s value is null, as a Stream<Void>. Throws an IllegalArgumentException if the function has parameters.

<T> T run(KRPC.Expression function, Object... args)#

Runs a server side function within a single physics tick, and returns its value. The value is null for a function with no value, and for a null value. The arguments are passed to the function’s parameters, with a number widened as Java widens it. An int or a long passes to an unsigned parameter of its width bit for bit, as the client holds unsigned values in signed types.

Throws an IllegalArgumentException if the number of arguments differs from the number of parameters, or if a parameter cannot take its argument.

KRPC.Expression compile(KRPC.Expression function)#

Compiles a server side function on the server, so that its first run is as fast as later ones, and returns the function.

Event addEvent(KRPC.Expression function)#

Creates an event from a server side function that evaluates to a boolean value, and returns an Event. Each call creates a new event.

Throws an IllegalArgumentException if the function does not evaluate to a boolean value, or has parameters.

krpc.schema.KRPC.ProcedureCall getCall(RemoteObject instance, String method, Object... args)#
krpc.schema.KRPC.ProcedureCall getCall(Class<?> clazz, String method, Object... args)#

Converts a call to a method of a remote object, or of a class as for addStream, into a procedure call message. The message is for a server side function built with the expression API. See The Expression API.

Throws an IllegalArgumentException if there is no method of that name taking the arguments.

krpc.schema.KRPC.ProcedureCall getCallTemplate(Class<?> clazz, String method)#

The call template of a member, a procedure call message that names the procedure and carries no arguments, for Expression.callWithArguments to supply each one. The member is named through its class or service, with no instance, by the name of its method, such as getCallTemplate(SpaceCenter.Engine.class, "getHasFuel"). A property’s setter is named set<Name>.

Throws an IllegalArgumentException if the class has no remote procedure of that name.

class Stream<T>#

A stream. See Streaming Data.

Two stream objects are equal, and have the same hashCode, when they refer to the same stream on the server. Streams order by their ids, so they can be sorted and used as the keys of a TreeMap.

T get()#

Returns the most recent value of the stream, waiting for the first value if none has arrived yet. Throws the exception that ended the stream, if it has ended, and a CancellationException if the thread is interrupted.

Object getCondition()#

The condition variable, notified with notifyAll when the value of the stream changes, and when the stream ends.

void waitForUpdate()#

Blocks until the value of the stream changes. Hold getCondition() when calling this method.

Throws the exception that ended the stream, if it ends before or during the wait, and a CancellationException if the thread is interrupted. A thread holding the condition sees an ending as an update: the wait returns, and later reads and waits throw the exception.

boolean waitForUpdateWithTimeout(double timeout)#

Blocks until the value of the stream changes, or the timeout elapses. Returns true if the value changed, and false on a timeout. Hold getCondition() when calling this method.

The timeout is in seconds, and Double.POSITIVE_INFINITY waits indefinitely. Throws an IllegalArgumentException for a negative or NaN timeout. Throws the exception that ended the stream, if it ends before or during the wait, and a CancellationException if the thread is interrupted. A thread holding the condition sees an ending as an update: the wait returns true, and later reads and waits throw the exception.

float getRate()#
void setRate(float rate)#

The update rate of the stream, in Hertz. Zero, the default, means no limit.

int addCallback(java.util.function.Consumer<T> callback)#

Adds a callback, called with each new value of the stream, and returns a tag for it. If the stream already has a value, the callback is called with it straight away. The exception that ends a stream goes to its end callbacks.

void removeCallback(int tag)#

Removes the callback with the given tag.

int addEndCallback(java.util.function.Consumer<Exception> callback)#

Adds a callback, called once when the stream ends, with the exception that ended it, and returns a tag for it. It is called straight away if the stream has already ended.

void removeEndCallback(int tag)#

Removes the end callback with the given tag.

void remove()#

Removes the stream from the server. Other streams of the same call are not affected.

void close()#

Removes the stream, as remove does, at the end of a try-with-resources block.

class Event#

An event, made from a stream of Boolean that is true when the event fires. See Events.

Two event objects are equal, and have the same hashCode, when they refer to the same stream on the server. Events order as their streams do.

void waitFor()#

Blocks until the event fires. Returns straight away if the event has fired since the previous wait on this event object. Hold getCondition() when calling this method.

Throws the exception that ended the event, if it ends before or during the wait, and a CancellationException if the thread is interrupted.

boolean waitForWithTimeout(double timeout)#

Blocks until the event fires, or the timeout elapses. Returns straight away if the event has fired since the previous wait on this event object. Returns true if the event fired, and false on a timeout. Hold getCondition() when calling this method.

The timeout is in seconds, and Double.POSITIVE_INFINITY waits indefinitely. Throws an IllegalArgumentException for a negative or NaN timeout. Throws the exception that ended the event, if it ends before or during the wait, and a CancellationException if the thread is interrupted.

Object getCondition()#

The condition variable, notified with notifyAll when the event fires, and when it ends.

int addCallback(java.lang.Runnable callback)#

Adds a callback, called each time the event fires, and returns a tag for it. It is called straight away for a firing that no wait has returned for and no callback has been called for.

void removeCallback(int tag)#

Removes the callback with the given tag.

int addEndCallback(java.util.function.Consumer<Exception> callback)#

Adds a callback, called once when the event ends, with the exception that ended it, and returns a tag for it. It is called straight away if the event has already ended.

void removeEndCallback(int tag)#

Removes the end callback with the given tag.

void remove()#

Removes the event from the server.

void close()#

Removes the event, as remove does, at the end of a try-with-resources block.

Stream<Boolean> getStream()#

The stream the event is made from.

abstract class RemoteObject#

The base class of remote objects. Two remote objects are equal, and have the same hashCode, when they refer to the same object on the server. Remote objects order by their ids, compared as unsigned integers.

static long getObjectId(RemoteObject obj)#

The identifier of a remote object on the server, e.g. to pass to constantObject. Throws an IllegalArgumentException if the object is null.

class RemoteException extends RuntimeException#

The base of every exception the client throws of its own.

class ConnectionException extends RemoteException#

Thrown when connecting fails, and by each call once the connection has closed or failed.

ConnectionResponse.Status getStatus()#

The status the server refused the connection with, such as DENIED, or null.

Disconnect.Reason getReason()#

The reason the server gave for ending the connection, such as SERVER_STOPPED, or null.

class ServerException extends RemoteException#

Thrown for an error from the server with no Java exception type. The base class of the exception classes of the services.

class StreamException extends RemoteException#

Thrown by a stream or event that you or the server removed, or that cannot be created.

class EncodingException extends RemoteException#

Thrown when a value cannot be encoded or decoded.

Service API Reference#