C##

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

Installing the Library#

The library is a NuGet package, available from nuget.org or downloaded from GitHub. It targets .NET Standard 2.0, and runs on .NET 5 or later, .NET Core 2.0 or later, .NET Framework 4.7.2 or later, and Mono.

To install using the .NET CLI:

dotnet add package KRPC.Client

NuGet also installs the package’s dependency, Google.Protobuf.

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 function.

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 Timeout.InfiniteTimeSpan as the handshakeTimeout to wait indefinitely for the player.

Over TCP/IP#

Select “Protobuf over TCP/IP” as the server’s protocol. Constructing a Connection connects to it. 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:

using System;
using KRPC.Client;
using KRPC.Client.Services.KRPC;

class Program {
    public static void Main() {
        var connection = new Connection();
        Console.WriteLine(connection.KRPC().GetStatus().Version);
    }
}

The constructor also takes the address and port of the server, and a name for the connection. These match the address and port shown in the server window. The address is an IPAddress. The name appears in the server window in the game:

using System;
using System.Net;
using KRPC.Client;
using KRPC.Client.Services.KRPC;

class Program {
    public static void Main() {
        var connection = new Connection(
            name: "My Example Program",
            address: IPAddress.Parse("192.168.1.10"),
            port: 1000);
        Console.WriteLine(connection.KRPC().GetStatus().Version);
    }
}

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. ConnectLocal connects to it, and returns a Connection as the constructor does. The following connects to a server with the default settings, at the default socket path for your platform, and prints its version:

using System;
using KRPC.Client;
using KRPC.Client.Services.KRPC;

class Program {
    public static void Main() {
        var connection =
            Connection.ConnectLocal(name: "My Example Program");
        Console.WriteLine(connection.KRPC().GetStatus().Version);
    }
}

ConnectLocal also takes a path, 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#

Use the connection in a using statement to close it at the end of the block:

using System;
using KRPC.Client;
using KRPC.Client.Services.KRPC;

class Program {
    public static void Main() {
        using (var connection =
                   new Connection(name: "My Example Program")) {
            Console.WriteLine(connection.KRPC().GetStatus().Version);
        }
    }
}

Dispose closes a connection explicitly. 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 ActiveVessel, an object of type Vessel. It sets the vessel’s name, then prints its altitude:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();
        var vessel = spaceCenter.ActiveVessel;
        vessel.Name = "My Vessel";
        var flightInfo = vessel.Flight();
        Console.WriteLine(flightInfo.MeanAltitude);
    }
}

Each service is an extension method of the connection, such as connection.SpaceCenter() for the SpaceCenter service. The method and the service’s classes are in a namespace for the service, such as KRPC.Client.Services.SpaceCenter. Your editor’s code completion lists the classes, enumerations, procedures and properties of a service.

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:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        try {
            connection.SpaceCenter().Load("missing");
        } catch (ArgumentException exception) {
            Console.WriteLine(
                "Failed to load the save: " + exception.Message);
        }
    }
}

The exception you catch depends on the error:

Every exception of the client’s own derives RemoteException. A .NET exception does not.

Values#

Procedures take and return C# values, such as int, string, IList and IDictionary, and null for a null. The services also define their own types:

  • A class is a remote object, described below.

  • A structure is a struct.

  • An enumeration is an enum, with [Flags] for a flags enumeration.

Flags Enumerations#

A flags enumeration, such as MapFilterType, holds any combination of its values. It is an enumeration with the [Flags] attribute. You combine values with |, and test for one with HasFlag:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();

        // Show only probes and ships in map mode
        spaceCenter.MapFilter = MapFilterType.Probes | MapFilterType.Ships;

        // Check whether map mode shows debris
        Console.WriteLine(
            spaceCenter.MapFilter.HasFlag(MapFilterType.Debris));

        // Show debris as well
        spaceCenter.MapFilter |= MapFilterType.Debris;
    }
}

~ complements every bit, including the bits the enumeration does not declare. The server rejects the result, so you use ~ only to remove flags with &, as in filter & ~MapFilterType.Debris.

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:

using System;
using System.Threading;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();
        var vessel = spaceCenter.ActiveVessel;
        var flightInfo = vessel.Flight();

        // Each read gets the current altitude from the game
        Console.WriteLine(flightInfo.MeanAltitude);
        Thread.Sleep(1000);
        Console.WriteLine(flightInfo.MeanAltitude);

        // Two objects for the same vessel are equal
        Console.WriteLine(vessel == spaceCenter.ActiveVessel);
    }
}

Two objects for the same thing in the game compare equal, and can be used as dictionary keys. Objects are also ordered, so they can be sorted or used as SortedDictionary keys.

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. In a stream, the connection the stream is added on runs the call:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        using (var connection = new Connection()) {
            var vessel = connection.SpaceCenter().ActiveVessel;
            var frame = vessel.Orbit.Body.ReferenceFrame;

            // Call a method on an object
            Console.WriteLine(vessel.Position(frame));

            // Call a static method, passing the connection first
            Console.WriteLine(
                Orbit.ReferencePlaneDirection(connection, frame));

            // Stream it
            var direction = connection.AddStream(
                () => Orbit.ReferencePlaneDirection(connection, frame));
            Console.WriteLine(direction.Get());
        }
    }
}

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

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        using (var connection = new Connection()) {
            var frame =
                connection.SpaceCenter().ActiveVessel.ReferenceFrame;

            // Bind the static methods to the connection once
            var orbit = Orbit.Bind(connection);
            Console.WriteLine(orbit.ReferencePlaneNormal(frame));
            Console.WriteLine(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:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();
        var vessel = spaceCenter.ActiveVessel;
        var refFrame = vessel.Orbit.Body.ReferenceFrame;
        while (true)
            Console.WriteLine(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:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();
        var vessel = spaceCenter.ActiveVessel;
        var refFrame = vessel.Orbit.Body.ReferenceFrame;
        var posStream =
            connection.AddStream(() => vessel.Position(refFrame));
        while (true)
            Console.WriteLine(posStream.Get());
    }
}

AddStream creates the stream from a lambda expression that makes the call, and returns a Stream. Calling Get returns the stream’s latest value.

A property is streamed with a lambda that reads it, such as () => flight.MeanAltitude.

A lambda that makes one call with fixed arguments streams that call. The object the call is made on is evaluated once, when the stream is created. Any other lambda is compiled into a server side function, which the server evaluates on each update.

Each call to AddStream creates another stream. A lambda with no value, such as a call to a procedure with no return value, streams as a Stream with no type parameter. It runs on each update for its effects.

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 using statement removes a stream at the end of the block:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();
        var flight = spaceCenter.ActiveVessel.Flight();
        using (var altitude =
                   connection.AddStream(() => flight.MeanAltitude)) {
            for (var i = 0; i < 10; i++)
                Console.WriteLine(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. Set Rate to limit how many times a second the stream updates:

using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var flightInfo = connection.SpaceCenter().ActiveVessel.Flight();
        var altitude = connection.AddStream(() => flightInfo.MeanAltitude);
        // Update the stream at most 10 times a second
        altitude.Rate = 10;
    }
}

Waiting for Changes#

Each stream has a condition variable, an object you lock with the lock statement. Wait blocks until the stream’s value changes. The following waits for the abort button to be pressed:

using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var control = connection.SpaceCenter().ActiveVessel.Control;
        var abort = connection.AddStream(() => control.Abort);
        lock (abort.Condition) {
            while (!abort.Get())
                abort.Wait();
        }
    }
}

Lock the condition when you call Wait, as the lock statement 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.

Wait 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:

using System;
using System.Threading;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var control = connection.SpaceCenter().ActiveVessel.Control;
        var abort = connection.AddStream(() => control.Abort);

        abort.AddCallback(
            (bool x) => {
                Console.WriteLine("Abort 1 called with a value of " + x);
            });
        abort.AddCallback(
            (bool x) => {
                Console.WriteLine("Abort 2 called with a value of " + x);
            });

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

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. Calling Get or Wait then throws the exception that ended it. The following streams the temperature of a part until the part is destroyed:

using System;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var part = connection.SpaceCenter().ActiveVessel.Parts.Root;
        var temperature = connection.AddStream(() => part.Temperature);
        try {
            lock (temperature.Condition) {
                while (true) {
                    temperature.Wait();
                    Console.WriteLine("Temperature " + temperature.Get());
                }
            }
        } catch (ObjectDestroyedException) {
            Console.WriteLine("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:

using System;
using System.Threading;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var part = connection.SpaceCenter().ActiveVessel.Parts.Root;
        var temperature = connection.AddStream(() => part.Temperature);

        temperature.AddCallback(
            (double value) => {
                Console.WriteLine("Temperature " + value);
            });
        temperature.AddEndCallback(
            (Exception error) => {
                Console.WriteLine("The stream ended: " + error.Message);
            });

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

Server Side Functions#

A server side function is a lambda expression in your program that runs inside the game. The client compiles it and sends it to the server, which runs it there. The following reads the vessel’s altitude and speed together:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var vessel = connection.SpaceCenter().ActiveVessel;
        var flight = vessel.Flight(vessel.Orbit.Body.ReferenceFrame);

        // Run the lambda on the server, so both values come from the same
        // physics tick
        var result = connection.Run(
            () => Tuple.Create(flight.MeanAltitude, flight.Speed));
        Console.WriteLine("Altitude: " + result.Item1 + " m, " +
                          "speed: " + result.Item2 + " m/s");
    }
}

Writing Server Side Functions describes what a function can contain. The server side functions guide 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.

Use Run for a function with effects, such as a call of ActivateNextStage. A stream or an event evaluates its function on every update, which repeats the effects.

Streaming a Function#

Pass AddStream a lambda that does more than make one call, 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:

using System;
using System.Threading;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();
        var flight = spaceCenter.ActiveVessel.Flight();

        // Stream the vessel's altitude in kilometers,
        // computed on the server
        var stream = connection.AddStream(() => flight.MeanAltitude / 1000);
        while (true) {
            Console.WriteLine("Altitude: " + stream.Get() + " km");
            Thread.Sleep(1000);
        }
    }
}

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. A lambda holds a single expression, so build the function with the expression API, and catch the exception with TryCatch:

var e = Expression.Bind(connection);
var altitude = e.Variable(
    "altitude", Type.Bind(connection).Double());
var function = e.BlockWithVariables(
    new List<Expression> { altitude },
    new List<Expression> {
        e.TryCatch(
            e.Assign(altitude, connection.Compile(
                () => flight.MeanAltitude / 1000)),
            "KRPC", "ObjectNotLoadedException", null,
            e.Assign(altitude, e.ConstantDouble(0))),
        altitude
    });
var stream = connection.AddStream<double>(function);

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 tells your program when it becomes true. The following waits until the vessel’s altitude exceeds 1000 meters:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();
        var flight = spaceCenter.ActiveVessel.Flight();

        // Create an event that triggers when the lambda returns true
        var evnt = connection.AddEvent(() => flight.MeanAltitude > 1000);

        // Wait on the event
        lock (evnt.Condition) {
            evnt.Wait();
            Console.WriteLine("Altitude reached 1000m");
        }
    }
}

AddEvent creates the event, and Wait 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 using statement removes an event at the end of the block:

using System;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();
        var flight = spaceCenter.ActiveVessel.Flight();
        var e = Expression.Bind(connection);
        var expr = e.GreaterThan(
            e.Call(Connection.GetCall(() => flight.MeanAltitude)),
            e.ConstantDouble(1000));
        using (var evnt = connection.AddEvent(expr)) {
            lock (evnt.Condition) {
                evnt.Wait();
                Console.WriteLine("Altitude reached 1000m");
            }
        }
        // The event was removed at the end of the block
    }
}

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

Event Callbacks#

An event can also call a callback each time it fires. The callback takes no arguments:

using System;
using System.Threading;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var flight = connection.SpaceCenter().ActiveVessel.Flight();

        var evnt = connection.AddEvent(() => flight.MeanAltitude > 1000);
        evnt.AddCallback(
            () => {
                Console.WriteLine("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:

using System;
using System.Threading;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var vessel = connection.SpaceCenter().ActiveVessel;
        var flightInfo = vessel.Flight(vessel.Orbit.Body.ReferenceFrame);

        // Both threads make calls over the same connection
        var threads = new[] {
            new Thread(() => {
                for (var i = 0; i < 10; i++)
                    Console.WriteLine(
                        "Altitude: " + flightInfo.MeanAltitude);
            }),
            new Thread(() => {
                for (var i = 0; i < 10; i++)
                    Console.WriteLine("Speed: " + flightInfo.Speed);
            })
        };
        foreach (var thread in threads)
            thread.Start();
        foreach (var thread in threads)
            thread.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 lock statement.

When one thread closes the connection, or the connection fails, the calls and waits of the other threads end with ConnectionException. A wait on a stream or an event that another thread removes ends with StreamException.

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 marks it as deprecated, and names the replacement. The member carries the [Obsolete] attribute, so the C# compiler warns where you use it, with a message naming the replacement.

Writing Server Side Functions#

The client includes a compiler, which converts a lambda expression into a server side function automatically when you pass it to Run, AddStream or AddEvent. This section describes what a function can contain, and how to compile one ahead of time.

Remote Calls and Constants#

The compiler translates the lambda’s expression tree into a server side function that computes the same result on the server, inside the game. Each part of the function either runs on the server or becomes a constant:

  • Property accesses and method calls on remote objects and services become calls in the function, made again on each evaluation. This includes calls on the elements of a collection in a LINQ operator. The procedures of the KRPC service cannot be called. They build and run server side functions and add streams, which a function would repeat on every evaluation.

  • Reading a field of a structure a service defines reads that field of it on the server. Constructing one with new builds it there. Comparing two with <, >, <= or >= is an error.

  • Captured variables, literals and any sub-expression that makes no remote call are evaluated once, when the function is compiled, and embedded as constants. An auto-property is read once too, as a captured variable is. A captured value in a string concatenation is formatted on the client, as C# formats it.

The compiler throws CompilationException for code that would run on the client, or only once, when compiling, where you would expect it to run on every evaluation:

  • A delegate call, and a call to a method, a constructor, a computed property or an operator defined outside the .NET base library and the kRPC client. Call it outside the lambda and use its result.

  • Passing a delegate, or a value whose type overrides a method such as ToString, to the base library, as in "a" + obj, list.Select(MyMethod) and your own IEnumerable<T> or IComparer<T> given to LINQ. So is reading Lazy<T>.Value.

  • Reading a stream with Get, as the stream would be read once. Make the stream’s remote procedure call in the lambda instead.

  • A lambda passed to AddEvent or AddStream that makes no remote procedure call, as its value is the same on every update. A function compiled with Compile first is not checked.

  • An System.Action lambda that makes no remote procedure call, as it has no effect on the server.

Operators#

  • Operators, conditional expressions, casts and indexing compile to the matching expression operators.

  • && and || short-circuit on the server. & and | evaluate both operands.

A function combines and tests the values of a flags enumeration with |, &, ^, ~ and HasFlag:

using System;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var spaceCenter = connection.SpaceCenter();

        // Stream whether map mode shows both probes and ships, computed on
        // the server
        var craft = MapFilterType.Probes | MapFilterType.Ships;
        var showsCraft = connection.AddStream(
            () => spaceCenter.MapFilter.HasFlag(craft));
        Console.WriteLine(showsCraft.Get());
    }
}

In a function, ~ keeps to the declared values. A comparison is the exception, as C# compares the numbers of the values. x == ~MapFilterType.Debris is never true, and x == (MapFilterType.All & ~MapFilterType.Debris) is the comparison you want.

Null Values#

  • Comparing a value with null tests whether it is null. ??, HasValue, Value and GetValueOrDefault behave as in C#.

  • An ordering comparison with a nullable number is false when the number is null. Arithmetic and logic on a null throw.

Collections#

  • List, HashSet and Dictionary initializers, Tuple.Create, and a tuple’s Item1 to Item7 compile to the matching expression operators. A dictionary’s Keys and Values are lists of its keys and values.

  • The LINQ operators Select, Where, SelectMany, Any and All with a predicate, Count, Sum, Min, Max and Average without one, Contains, OrderBy, Concat, Skip, Take, First, Last, ElementAt, Distinct, Reverse, Union, Intersect, Except, Zip, ToDictionary, ToList and ToHashSet compile to the server’s collection operations.

  • A lambda that evaluates to an IEnumerable<T> evaluates to a list. One that evaluates to the IOrderedEnumerable<T> of OrderBy is an error. Call ToList on it.

Library Methods#

  • The System.Math methods Abs, Sign, Min, Max, Clamp, Floor, Ceiling, Round, Pow, Sqrt, Exp, Log, Log10, Sin, Cos, Tan, Asin, Acos, Atan and Atan2 take server side arguments. Integer Abs, Min, Max and Clamp are exact at their own type. Math.Round takes the MidpointRounding.ToEven and AwayFromZero modes, given as a client side value.

  • Console.WriteLine writes a line to the game’s log with Print. It formats its arguments as string.Format does. Convert a number computed on the server with ToString(CultureInfo.InvariantCulture) before passing it.

  • The string members Length, Substring, IndexOf, Contains, StartsWith, EndsWith, Replace, ToUpperInvariant, ToLowerInvariant, Trim, TrimStart and TrimEnd compile to the server’s string operations. So does string.Join.

  • An interpolated string, string.Concat, and string.Format with plain {0} placeholders compile to a concatenation.

Culture#

The server formats and compares strings with the invariant culture. A call that depends on the current culture is an error:

  • A number converts to a string with ToString(CultureInfo.InvariantCulture). Format an interpolated string with FormattableString.Invariant, or call string.Format with CultureInfo.InvariantCulture.

  • IndexOf, StartsWith and EndsWith with a string argument take StringComparison.Ordinal.

  • ToUpper and ToLower take CultureInfo.InvariantCulture.

  • OrderBy with a string key takes StringComparer.Ordinal.

Statements#

The lambda is a C# expression tree, so C#’s expression tree rules apply. It holds a single expression, and a call in it gives every argument, including the optional ones. Build a function with statements, or one that throws or handles exceptions, with the expression API.

Differences from C##

Some results differ from C#’s, as the server computes with its own operations:

  • Integer arithmetic wraps around on overflow, so checked arithmetic is an error.

  • == and != compare tuples and collections by their contents. C# compares them by reference.

  • Math.Round takes any number of decimal places, and a negative number rounds to tens, hundreds and beyond.

  • ToString of an object computed on the server gives the server’s name for its class, which differs from the client’s.

  • A double converted to a string on the server is formatted by the server’s runtime. It can print fewer digits than the client, as in 0.3 for 0.30000000000000004.

  • An index out of range in list[i], ElementAt or Substring throws System.IndexOutOfRangeException, where C# throws System.ArgumentOutOfRangeException.

  • A key repeated in ToDictionary takes the last of its values, where C# throws.

Unsupported Constructs#

A construct with no server side equivalent throws CompilationException naming it. Examples are GroupBy, Aggregate, MinBy, MaxBy and a format specifier.

Compiling Ahead of Time#

Pass a lambda expression to Compile to compile it into a server side function. AddEvent, AddStream and Run take the result, and run it without compiling it again. The following compiles a function once, and runs it every second:

using System;
using System.Threading;
using KRPC.Client;
using KRPC.Client.Services.SpaceCenter;

class Program {
    public static void Main() {
        var connection = new Connection();
        var resources = connection.SpaceCenter().ActiveVessel.Resources;

        // Compile the lambda once. Its remote procedure calls
        // are made again each time the function runs
        var fuelFraction = connection.Compile(
            () => resources.Amount("LiquidFuel") /
                  resources.Max("LiquidFuel"));

        // Run the compiled function as often as needed
        while (true) {
            Console.WriteLine(
                "Fuel: " + connection.Run<float>(fuelFraction));
            Thread.Sleep(1000);
        }
    }
}

Given a lambda, AddEvent and Run compile it again on every call. So does AddStream, unless the lambda makes one call with fixed arguments. Its captured variables take their current values each time. A compiled function keeps the values from when it was compiled. Compiling makes a remote procedure call per node.

To use a lambda repeatedly, compile it once with Compile and pass the result. Compile also compiles the function on the server, so its first run is as fast as later ones.

Parameters#

A lambda passed to Compile can take up to four parameters. Run passes its arguments to them:

var flight = connection.SpaceCenter().ActiveVessel.Flight();
var altitudeAbove = connection.Compile(
    (double height) => flight.MeanAltitude - height);
Console.WriteLine(connection.Run<double>(altitudeAbove, 70000));

An argument is encoded at its parameter’s type, and a number widens as C# widens it. A signed integer that is not negative converts to an unsigned parameter at least as wide, so a long converts to a ulong but not a uint. An array other than an object[], passed as the only argument, is the argument of a function with one parameter.

An event or a function stream runs its function with no arguments. Passing AddStream a lambda with parameters throws CompilationException.

Service Stubs#

The client includes code for each service that ships with kRPC, generated from the services of one kRPC release and compiled into KRPC.Client.dll. These stubs are the classes and extension methods in the KRPC.Client.Services namespaces.

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. Each service is an extension method of it, such as SpaceCenter(). Disposing of it closes the connection.

The KRPC service, from KRPC(), provides the server’s basic functionality. The client calls some of its procedures itself, such as to add and remove streams.

Connection (string name = "", IPAddress address = null, int port = 50000, TimeSpan timeout = default, TimeSpan? handshakeTimeout = null, TimeSpan? stallTimeout = null)#

Connects to a kRPC server over TCP/IP.

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

  • address – The address of the server. Defaults to 127.0.0.1 when null.

  • port – The port of the server. Defaults to 50000.

  • timeout – 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 – How long to wait for the server to accept the connection. Defaults to 5 seconds when null. Timeout.InfiniteTimeSpan waits indefinitely, such as for a server that asks the player to approve each connection.

  • stallTimeout – 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 when null. Timeout.InfiniteTimeSpan waits indefinitely.

Throws ConnectionException if the connection fails or the server refuses it. Throws System.ArgumentOutOfRangeException for a negative timeout, or a handshake or stall timeout that is neither positive nor infinite.

static Connection ConnectLocal (string name = "", string path = "", TimeSpan? handshakeTimeout = null, TimeSpan? stallTimeout = null)#

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 – A name for the connection, shown in the server window in the game.

  • path – The path of the server’s socket, shown in the server window in the game. An empty path, the default, is the one the server uses unless it was configured with another.

  • handshakeTimeout – As for the constructor.

  • stallTimeout – As for the constructor.

Throws ConnectionException and System.ArgumentOutOfRangeException as the constructor does.

void Dispose ()#

Closes the connection. Disposing of a connection that is already closed does nothing.

Stream<TResult> AddStream<TResult> (Expression<Func<TResult>> expression)#

Creates a stream from a lambda expression with no parameters, and returns a Stream. Each call creates a new stream. A lambda that makes one remote procedure call with fixed arguments streams that call. Any other lambda is compiled into a server side function on every call, which the stream evaluates on each update. Throws CompilationException if the lambda cannot be compiled, or makes no remote procedure call.

Stream<TResult> AddStream<TResult> (LambdaExpression expression)#

Creates a stream as the overload above does, for a lambda of any delegate type. Throws CompilationException for a lambda with parameters, and an System.ArgumentException if TResult cannot hold the lambda’s value.

Stream AddStream (Expression<Action> expression)#

Creates a stream from a lambda expression with no value, which runs on each update for its effects. A lambda that makes one remote procedure call with fixed arguments streams that call. Any other lambda is compiled into a server side function on every call. Throws an System.ArgumentException if the lambda’s body has a value, and CompilationException if the lambda cannot be compiled.

Stream<TResult> AddStream<TResult> (KRPC.Client.Services.KRPC.Expression function)#

Creates a stream of the value of a server side function, which takes no arguments. Throws an System.ArgumentException if the function has no value, takes parameters, or TResult cannot hold its value.

Stream AddStream (KRPC.Client.Services.KRPC.Expression function)#

Creates a stream of a server side function with no value, which runs on each update for its effects. Throws an System.ArgumentException if the function has a value.

TResult Run<TResult> (Expression<Func<TResult>> expression)#

Runs a lambda expression on the server, within a single physics tick, and returns its value. The lambda is compiled into a server side function on every call. Throws CompilationException if the lambda cannot be compiled.

void Run (Expression<Action> expression)#

Runs a lambda expression with no value on the server, within a single physics tick. Throws CompilationException if the lambda cannot be compiled, or makes no remote procedure call.

TResult Run<TResult> (KRPC.Client.Services.KRPC.Expression function, params object[] args)#

Runs a server side function within a single physics tick, and returns its value. The arguments are passed to the function’s parameters. A null value needs a reference type or a nullable value type as TResult.

Throws an System.ArgumentException if the function has no value, the number of arguments is wrong, a parameter cannot take its argument, or TResult cannot hold the function’s value.

void Run (KRPC.Client.Services.KRPC.Expression function, params object[] args)#

Runs a server side function with no value within a single physics tick. The arguments are passed to the function’s parameters, as for the overload above.

Event AddEvent (Expression<Func<bool>> expression)#

Creates an event from a lambda expression that evaluates to a boolean value, and returns an Event. The lambda is compiled into a server side function on every call. Throws CompilationException if the lambda cannot be compiled, or makes no remote procedure call.

Event AddEvent (KRPC.Client.Services.KRPC.Expression function)#

Creates an event from a server side function that takes no arguments and evaluates to a boolean value. Throws an System.ArgumentException if the function takes parameters, or does not evaluate to a boolean value.

KRPC.Client.Services.KRPC.Expression Compile<TResult> (Expression<Func<TResult>> expression)#

Compiles a lambda expression into a server side function. The server compiles the function too, so its first run is as fast as later ones. Throws CompilationException for a construct with no server side equivalent. See Writing Server Side Functions.

KRPC.Client.Services.KRPC.Expression Compile (Expression<Action> expression)#

Compiles a lambda expression with no value into a server side function.

KRPC.Client.Services.KRPC.Expression Compile<T1, TResult> (Expression<Func<T1, TResult>> expression)#

Compiles a lambda expression with a parameter into a server side function. Overloads take up to four parameters, with or without a value.

KRPC.Client.Services.KRPC.Expression Compile (KRPC.Client.Services.KRPC.Expression function)#

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

static KRPC.Schema.KRPC.ProcedureCall GetCall<TResult> (Expression<Func<TResult>> expression)#

Converts a lambda expression that makes one remote procedure call into a KRPC.Schema.KRPC.ProcedureCall message, for use in a server side function built with the expression API. See The Expression API. Throws an System.ArgumentException if the lambda does more than make one call, or calls a member that is not a remote procedure.

static KRPC.Schema.KRPC.ProcedureCall GetCall (Expression<Action> expression)#

Converts a lambda expression that makes one call to a procedure with no return value, as the overload above does.

static KRPC.Schema.KRPC.ProcedureCall GetCall (LambdaExpression expression)#

Converts a lambda expression of any delegate type, as the overload above does.

static KRPC.Schema.KRPC.ProcedureCall GetCallTemplate<T, TResult> (Expression<Func<T, TResult>> expression)#

The call template of a member of a class, a KRPC.Schema.KRPC.ProcedureCall message that names the procedure and carries no arguments, for CallWithArguments to supply each one. The lambda reads a property or calls a method of its parameter, such as (Engine e) => e.HasFuel, and is not evaluated. Throws an System.ArgumentException if the lambda does more than that, or names a member that is not a remote procedure.

static KRPC.Schema.KRPC.ProcedureCall GetCallTemplate<T> (Expression<Action<T>> expression)#

The call template of a method with no return value, as the overload above.

static KRPC.Schema.KRPC.ProcedureCall GetCallTemplate<TResult> (Expression<Func<TResult>> expression)#

The call template of a member of a service, or of a static method. The lambda takes no parameter, such as () => connection.SpaceCenter ().UT, and its arguments are not evaluated. Throws an System.ArgumentException if the lambda names a member of an object, which takes the overload above.

static KRPC.Schema.KRPC.ProcedureCall GetCallTemplate (Expression<Action> expression)#

The call template of a procedure with no return value, as the overload above.

static KRPC.Schema.KRPC.ProcedureCall GetSetCallTemplate<T> (string property)#

The call template of a property’s setter, on a class or on a service’s Service class, named as nameof (Engine.Throttle). Throws an System.ArgumentException if the property has no setter that is a remote procedure. Functions and Collections uses a call template.

class RemoteObject#

The base class of remote objects. Two objects with the same identifier are equal, and hash equal. CompareTo and the comparison operators order objects by their identifiers.

static ulong GetObjectId (RemoteObject obj)#

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

class Stream#

A stream. See Streaming Data. A stream of a call or function with no value runs on each update for its effects, and the server sends one update, after the first run. Two stream objects are equal if they are bound to the same stream on the server. Each call to AddStream creates a new stream, so two streams of the same call are not equal.

void Get ()#

Waits for the stream’s first update. Throws the exception that ended the stream, if it has ended.

bool Wait (double timeout = double.PositiveInfinity)#

Blocks until the stream updates, or the timeout elapses. Returns true if the stream updated, and false on a timeout. Lock Condition when calling this method.

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

object Condition { get; }#

A condition variable, locked with the lock statement, pulsed with Monitor.PulseAll when the stream updates.

float Rate { get; set; }#

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

int AddCallback (Action callback)#

Adds a callback, with no arguments, called each time the stream updates, and returns a tag for RemoveCallback. It is called straight away if the stream has updated. The exception that ends a stream goes to its end callbacks.

void RemoveCallback (int tag)#

Removes a callback, given the tag AddCallback returned.

int AddEndCallback (Action<Exception> callback)#

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

void RemoveEndCallback (int tag)#

Removes an end callback, given the tag AddEndCallback returned.

void Remove ()#

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

void Dispose ()#

Removes the stream, as Remove does, at the end of a using block. A failed connection throws no exception.

class Stream<TReturnType>#

A stream with a value, derived from Stream. The stream updates each time its value changes. It adds:

TReturnType 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.

int AddCallback (Action<TReturnType> callback)#

Adds a callback, called with each new value of the stream, and returns a tag for RemoveCallback. If the stream already has a value, the callback is called with it straight away.

class Event#

An event, made from a stream of bool that is true when the event fires. See Events. Two event objects are equal if they are bound to the same stream on the server.

bool Wait (double timeout = double.PositiveInfinity)#

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. Lock Condition when calling this method.

The timeout is in seconds, and an infinite timeout waits indefinitely. Throws an System.ArgumentOutOfRangeException for a negative or NaN timeout. Throws the exception that ended the event, if it ends before or during the wait.

object Condition { get; }#

A condition variable, locked with the lock statement, pulsed with Monitor.PulseAll when the event fires.

int AddCallback (Action callback)#

Adds a callback, with no arguments, called each time the event fires, and returns a tag for RemoveCallback. 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 a callback, given the tag AddCallback returned.

int AddEndCallback (Action<Exception> callback)#

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

void RemoveEndCallback (int tag)#

Removes an end callback, given the tag AddEndCallback returned.

void Remove ()#

Removes the event from the server.

void Dispose ()#

Removes the event, as Remove does, at the end of a using block. A failed connection throws no exception.

Stream<bool> Stream { get; }#

The stream the event is made from.

class RemoteException#

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

class ConnectionException#

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

KRPC.Schema.KRPC.ConnectionResponse.Types.Status? Status { get; }#

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

KRPC.Schema.KRPC.Disconnect.Types.Reason? Reason { get; }#

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

class ServerException#

Thrown for an error from the server with no .NET exception type, and the base of each exception class a service declares. Derives RemoteException.

class StreamException#

Thrown by a stream or event that you or the server removed, or that cannot be added. Derives RemoteException.

class EncodingException#

Thrown for a value that cannot be encoded or decoded, such as a null for a type that cannot hold one. Derives RemoteException.

class CompilationException#

Thrown when a lambda expression cannot be compiled into a server side function. The message names the unsupported construct. See Writing Server Side Functions. Derives RemoteException.

class IConnection#

The interface Connection implements, which the service stubs call.

Service API Reference#