Table of Contents

Java Client

The Java client runs on Java 11 or later and on Android API 24 or later. It is generated by NexNet.Generator together with its runtime as plain Java sources, so it needs no Maven artifact and has no runtime dependencies. Callbacks and results use CompletableFuture; the API works naturally from Kotlin.

Transport Config
WebSocket (ws://, wss://) ClientConfig.webSocket(URI)
HttpSocket (http://, https://) ClientConfig.httpSocket(URI)
TCP ClientConfig.tcp(host, port)
TCP + TLS ClientConfig.tcpTls(host, port)

Unix domain sockets and QUIC are not available in Java. See Multi-language Clients for the opt-in, the build options, the feature parity table and the type mapping.

1. The example API

The examples on this page use this API, defined in C# in the server's project:

[NexusObject]
public class ChatMessage
{
    [NexusKey(0)] public string User { get; set; } = "";
    [NexusKey(1)] public string Text { get; set; } = "";
}

public interface IChatClientNexus
{
    void Message(ChatMessage message);          // the server pushes a message
    ValueTask<string> GetStatus();              // the server asks the client
}

public interface IChatServerNexus
{
    void Send(string text);
    ValueTask<ChatMessage[]> History(int count, CancellationToken cancellationToken);
    ValueTask Upload(INexusDuplexPipe pipe, string fileName);
    ValueTask Subscribe(INexusDuplexChannel<ChatMessage> channel);

    [NexusCollection(NexusCollectionMode.BiDirectional)]
    INexusList<string> Rooms { get; }
}

[Nexus<IChatServerNexus, IChatClientNexus>(NexusType = NexusType.Server,
    Targets = NexusTargets.Java | NexusTargets.JavaScript)]
public partial class ChatServerNexus
{
    // server implementation
}

2. Generate the client

Configure the output directory and the Java package in the project that holds ChatServerNexus, then build it:

<PropertyGroup>
  <NexNetJavaOutputDir>../chat-java/src/generated/java</NexNetJavaOutputDir>
  <NexNetJavaPackage>com.example.chat</NexNetJavaPackage>
</PropertyGroup>
dotnet build

chat-java/src/generated/java/ now holds:

Path Contents
com/example/chat/ChatClient.java The factory: ChatClient.create(config, nexus)
com/example/chat/ChatServerProxy.java The server proxy
com/example/chat/ChatClientNexusBase.java The client nexus to extend
com/example/chat/ChatMessage.java The ChatMessage class (getters, setters, equals/hashCode)
com/example/chat/formatters/Formatters.java The serializers (Formatters.ChatMessage)
com/dtronix/nexnet/** The client runtime

Every build rewrites the folder (only files that changed), so do not edit it.

3. Add the sources to your build

The output directory is a source root. The sources compile with --release 11 or later, warnings included.

Gradle (Kotlin DSL):

plugins { java }

java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }   // or 11+
tasks.withType<JavaCompile>().configureEach { options.release = 11 }

sourceSets {
    main { java.srcDir("src/generated/java") }
}

Android (Gradle):

android {
    defaultConfig { minSdk = 24 }
    sourceSets["main"].java.srcDir("src/generated/java")
}

Maven: add the folder with build-helper-maven-plugin (add-source goal) or <sourceDirectory> when it is the only source root.

To share one runtime between several generated packages, generate the runtime once and build the others with <NexNetJavaEmitRuntime>false</NexNetJavaEmitRuntime>.

Nullness annotations. By default the generated code and runtime carry no annotations. For Kotlin null-safety or NullAway, build with <NexNetJavaNullness>jspecify</NexNetJavaNullness> and add compileOnly("org.jspecify:jspecify:1.0.0").

4. Connect

import com.dtronix.nexnet.client.ClientConfig;
import com.dtronix.nexnet.client.NexusClient;
import com.example.chat.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CompletableFuture;

final class ChatNexus extends ChatClientNexusBase {
    @Override
    protected void message(ChatMessage message) {
        System.out.println(message.getUser() + ": " + message.getText());
    }

    @Override
    protected CompletableFuture<String> getStatus() {
        return CompletableFuture.completedFuture("online");
    }

    @Override
    protected CompletableFuture<Void> onConnected(boolean isReconnected) {   // optional hook
        return CompletableFuture.completedFuture(null);
    }
}

ClientConfig config = ClientConfig.webSocket(URI.create("wss://chat.example.com/nexus"))
    .authenticate(() -> sessionToken.getBytes(StandardCharsets.UTF_8))
    .build();

NexusClient<ChatServerProxy> client = ChatClient.create(config, new ChatNexus());
client.connect().join();

client.proxy().send("hello");                                  // void: fire and forget
List<ChatMessage> history = client.proxy().history(20).join();
client.disconnect().join();
client.close();

HttpSocket over TLS, trusting a private CA, pinning the server key and presenting a client certificate:

TlsOptions tls = TlsOptions.builder()
    .trustCaCertificates(Files.readAllBytes(Path.of("ca.pem")), false)   // PEM or DER
    .pinCertificateSha256(spkiSha256)                                     // 32 bytes; optional
    .clientCertificatePkcs12(Files.readAllBytes(Path.of("client.pfx")), password)
    .build();

ClientConfig config = ClientConfig.httpSocket(URI.create("https://chat.internal:5001/nexus"))
    .tls(tls)
    .authorization("Bearer " + jwt)          // WebSocket/HttpSocket: an upgrade request header
    .build();
  • connect() fails its future when the connection fails; tryConnect() completes with a ConnectionResult instead. Both take an optional CancellationToken.
  • state() is a ConnectionState; addStateListener(state -> …) reports every change, in order.
  • disconnected() completes when the connection is over for good (after reconnection gave up).
  • isSecure() is false for ws://, http:// and plain TCP. Those log a warning once per client (when a logger is set).
  • Host names are verified and SNI is sent. TlsTrust builds trust managers from key stores, and computes certificate and SPKI pins (TlsTrust.spkiSha256(certificate)).
  • close() disconnects and waits for the client's threads; it is the only blocking method.
  • Builder options mirror the C# ClientConfig: connectionTimeoutMillis, handshakeTimeoutMillis, timeoutMillis, pingIntervalMillis, progressTimeoutMillis, invocationOptions, pipeOptions, header, queryToken, logger, reconnectionPolicy, callbackExecutor, invocationExecutor.

5. Authentication

The NexNet greeting token is the authentication mechanism every client supports. authenticate(Supplier<byte[]>) or authenticateAsync(Supplier<CompletableFuture<byte[]>>) runs before the transport connects, on every connect and reconnect, bounded by the handshake timeout. If it throws or times out, the connect fails with DisconnectReason.AUTHENTICATION and no connection is opened. The server checks the token in OnAuthenticate (see Authentication). A server method the client is not authorized for fails with NexusUnauthorizedException.

6. Invocations and errors

Proxy methods are camelCase. A C# method that returns ValueTask<T> returns a CompletableFuture<T>, ValueTask a CompletableFuture<Void>, and void returns nothing. Names that clash with Java keywords or Object methods get a trailing _ (notify_, hashCode_).

Futures complete on the callback executor, never on the network threads, so blocking in a continuation does not stall the connection. Exceptions (all unchecked):

Exception When
NexusTransportException (TransportError) Not connected, or the transport failed
NexusRemoteInvocationException (remoteErrorCode, remoteExceptionType, remoteMessage) The server method threw
NexusUnauthorizedException The server's OnAuthorize refused the call
NexusBusyException A pipe, channel or collection was refused (limit or authorization)
NexusMessageTooLargeException (size, limit) An argument exceeded the server's MaxMessageSize
java.util.concurrent.CancellationException The call was canceled, or the session ended while it was pending

Client nexus methods run on the invocation executor. Override onInvocationException(exception, methodId) to send your own NexusRemoteError to the server instead of the exception's details.

7. Cancellation

A C# CancellationToken parameter gives two overloads: one without it and one taking the runtime's com.dtronix.nexnet.CancellationToken.

try (CancellationTokenSource cts = new CancellationTokenSource()) {
    CompletableFuture<List<ChatMessage>> call = client.proxy().history(1000, cts.token());
    // ...
    cts.cancel();
}
  • Canceled before the call is sent: the future fails with CancellationException and nothing is sent.
  • Canceled after: the future completes canceled at once and the server method's CancellationToken is canceled.
  • future.cancel(true) on a returned future also cancels the call on the server.
  • In a client nexus method, the CancellationToken parameter is canceled when the server cancels the call or the session ends.

8. Duplex pipes

try (NexusDuplexPipe pipe = client.createPipe()) {
    client.proxy().upload(pipe, "report.pdf").join();   // completes once the invocation is sent
    pipe.ready().join();
    try (OutputStream out = pipe.outputStream()) {       // close() completes the output (half-close)
        out.write(fileBytes);
    }
    pipe.completed().join();
}
  • read() returns a future of the next ByteBuffer (null at the end); write(ByteBuffer) completes once the bytes are within the server's credit; completeOutput() half-closes.
  • inputStream() and outputStream() are blocking adapters: never use them on the Android main thread.
  • Credit is granted to the server only as you read, so a slow reader slows the server's writer, never the session.
  • close() releases the pipe. A pipe a client nexus method receives is closed when the method's future completes.
  • forwardTo(other) and NexusDuplexPipe.bridge(a, b) copy between pipes with backpressure. Their cancellable forms are forwardTo(other, CancellationToken) and NexusDuplexPipe.bridge(a, b, CancellationToken): a canceled forward or bridge stops and completes neither pipe (canceling the returned future does the same). A bridge returns once both directions half-closed; when one pipe ends while the other direction is still open (a reset, its session ending, its peer completing it) or a direction fails, it completes both pipes in both directions and returns (or fails with the direction's error).

9. Channels

import com.example.chat.formatters.Formatters;

NexusDuplexChannel<ChatMessage> channel = client.createChannel(Formatters.ChatMessage);
client.proxy().subscribe(channel).join();

NexusChannelReader<ChatMessage> reader = channel.reader().join();
reader.read().thenAccept(item -> item.ifPresent(m -> System.out.println(m.getText())));
List<ChatMessage> rest = reader.readUntilComplete().join();
  • NexusChannelReader: read() (Optional, empty at the end; for item types that can be null use readItem()), readBatch(max), readUntilComplete().
  • NexusChannelWriter (channel.writer()): write, writeAll, complete, writeAndComplete.
  • Built-in item types use com.dtronix.nexnet.serialization.Formatters (INT, STRING, …).
  • NexusDuplexChannel.over(pipe, formatter) reads a typed channel from an existing pipe.

10. Synchronized collections

NexusList<String> rooms = client.proxy().rooms();
rooms.addChangeListener(change -> refresh(new ArrayList<>(rooms)));   // on the callback executor
rooms.enable().join();                 // true once the initial state arrived
rooms.addAsync("general").join();      // BiDirectional only; true once the server applied it
rooms.disable().join();

NexusList<T> is a read-only java.util.List<T>; changes go through the …Async methods (addAsync, insertAsync, removeAsync, removeAtAsync, replaceAsync, moveAsync, clearAsync) and apply when the server's change arrives. ready() and disabled() follow the list's lifetime.

11. Reconnection

ClientConfig config = ClientConfig.tcpTls("chat.internal", 7000)
    .reconnectionPolicy(new DefaultReconnectionPolicy())   // 0, 2, 10, 30 s, then every 30 s
    .build();

Reconnection is off unless a policy is set. DefaultReconnectionPolicy(delaysMillis, continuous, reasons) customizes the delays and the DisconnectReasons it reconnects for (default: SOCKET_ERROR, TIMEOUT, SERVER_RESTARTING). The nexus gets onReconnecting() and then onConnected(true); client.reconnection() (addListener(ReconnectListener)) reports each attempt.

12. Client pool

NexusClientPool<ChatServerProxy> pool = new NexusClientPool<>(
    new NexusClientPoolConfig(config).maxConnections(8).maxIdleTimeMillis(120_000).minIdleConnections(1),
    () -> ChatClient.create(config, new ChatNexus()));

try (RentedNexusClient<ChatServerProxy> rented = pool.rent().join()) {
    rented.proxy().history(10).join();
}
pool.close();

pool.collectionConnector(ChatServerProxy::rooms) gives a collection on a pooled client.

13. Logging, metrics and diagnostics

ClientConfig config = ClientConfig.webSocket(uri)
    .logger((level, category, exception, message) -> System.out.println(level + " " + category + ": " + message))
    .build();

NexusMetrics.shared().track(client);                        // the C# instruments, same names and tags
NexusMetrics.shared().addListener(new NexusMetricsListener() {
    @Override public void add(NexusInstrument i, long value, Map<String, String> tags) { /* counters */ }
    @Override public void record(NexusInstrument i, double value, Map<String, String> tags) { /* histograms */ }
});

NexusSessionSnapshot snapshot = Diagnostics.snapshot(client);  // the C# NexusSessionSnapshot
  • Without a logger the runtime logs nothing (not even the plaintext warning). Loggers must be thread-safe and must not block.
  • The instruments follow Metrics & Diagnostics; NexusMetrics.collect(observer) reads the observable ones.

14. Types

Generated classes have a no-argument constructor (members at their C# initial values), an all-members constructor, getters and setters, and value equals/hashCode.

C# Java
byte, ushort / uint int / long (range-checked on write)
ulong long with the raw bits (UnsignedLongs to format or compare)
decimal java.math.BigDecimal
DateTime, TimeSpan, … runtime NexusDateTime, NexusTimeSpan, … (ticks; toEpochMillis(), toEpochSecond()/nanoOfSecond())
Guid java.util.UUID
T[], List<T> / Dictionary<K, V> / HashSet<T> java.util.List / Map / Set

No java.time type appears in the API (it needs Android API 26); convert with Instant.ofEpochSecond(dt.toEpochSecond(), dt.nanoOfSecond()) where java.time is available. The full table is in Multi-language Clients: Type mapping.

Threading

Thread Runs
nexnet-<id>-reader, nexnet-<id>-writer Network IO, one pair per connection. Never runs your code
Callback executor (callbackExecutor, default: a shared daemon pool) Completes every future you get, state listeners, list change listeners
Invocation executor (invocationExecutor, default: the shared pool) Client nexus methods and the onConnected/onDisconnected/onReconnecting hooks

Connecting does no IO on the calling thread, so connect() is safe to call from a UI thread; only waiting on its future (join(), get()) blocks.

Android notes

  • Add the generated folder to the app module's source set (above); the runtime uses only APIs present on API 24, and needs the INTERNET permission.
  • Pass the main-thread executor as callbackExecutor (ContextCompat.getMainExecutor(context)) to receive results and state changes on the UI thread. Never call join()/get() or the blocking pipe streams on the main thread.
  • Keep invocationExecutor on a background executor unless your client nexus methods only touch the UI.
  • Tie the client to a lifecycle: connect when the app comes to the foreground and disconnect() when it goes to the background, and set a reconnectionPolicy so the client recovers after the system drops the network. The optional android module (below) does this with NexusConnectionKeeper.
  • R8/ProGuard needs no keep rules: the runtime and the generated code use no reflection.

Kotlin

The API is plain Java, so Kotlin uses it directly; kotlinx.coroutines.future.await (kotlinx-coroutines) turns futures into suspending calls:

val client = ChatClient.create(config, ChatNexus())
client.connect().await()
val history = client.proxy().history(20).await()

Build with Nullness=jspecify to get Kotlin nullable types instead of platform types. The optional kotlin module (below) adds suspend functions with cancellation and Flow adapters.

Optional modules

Four optional modules add platform integrations on top of the core runtime. The generator emits none of them by default, because each needs third-party libraries that your build supplies. List the ones you want in EmitRuntimeModules; each is written beside the core runtime, in its own package, under the same source root:

<NexNetTarget Include="java" OutputDir="../chat-java/src/generated/java" Package="com.example.chat"
              EmitRuntimeModules="kotlin;okhttp" />
<!-- or, with the properties of section 2: -->
<NexNetJavaEmitRuntimeModules>kotlin;okhttp</NexNetJavaEmitRuntimeModules>
Module Adds Package
android NexusAndroid.mainThreadExecutor() and NexusAndroid.configure(builder), NexusConnectionKeeper (connects in the foreground, disconnects in the background, reconnects on network changes), AndroidNexusLogger (Logcat), NexusJavaTime (java.time converters on API 26+) com.dtronix.nexnet.android
kotlin connectAwait(), nexusCall { token -> … } (coroutine cancellation cancels the call), states(), NexusChannelReader.asFlow(), NexusList.changes() com.dtronix.nexnet.kotlin
okhttp OkHttpWebSocketConnector: the WebSocket transport over an OkHttpClient (pass it to ChatClient.create(config, nexus, connector)) com.dtronix.nexnet.okhttp
micrometer NexusMicrometerBinder: the client metrics as Micrometer meters with the C# names com.dtronix.nexnet.micrometer

Add each module's dependencies to your build. The versions are the ones the modules are built and tested with; any later compatible version works.

Module Third-party dependencies Build requirements
android androidx.lifecycle:lifecycle-process:2.11.0, androidx.annotation:annotation:1.11.0 An Android build (Android Gradle plugin, compileSdk 36, minSdk 24): the sources use android.* classes, so a plain JVM project cannot compile them. The app's manifest needs android.permission.INTERNET and, for NexusConnectionKeeper, android.permission.ACCESS_NETWORK_STATE
kotlin org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0 (and the Kotlin standard library, which the Kotlin plugin adds) The Kotlin Gradle plugin (org.jetbrains.kotlin.jvm or org.jetbrains.kotlin.android, Kotlin 2.x), which compiles the .kt files in the Java source root
okhttp com.squareup.okhttp3:okhttp:5.5.1 (brings Okio and the Kotlin standard library) None beyond Java 11
micrometer io.micrometer:micrometer-core:1.17.2 None beyond Java 11

For example, a Gradle project that emits kotlin and okhttp:

plugins {
    java
    kotlin("jvm") version "2.4.21"
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
    implementation("com.squareup.okhttp3:okhttp:5.5.1")
}

sourceSets {
    main { java.srcDir("src/generated/java") }
}
  • Nullness applies to the modules' Java sources as to the core runtime; the Kotlin sources carry no JSpecify annotations.
  • The modules need the emitted core runtime: listing one with EmitRuntime=false is NEXNET045, as is an unknown module name.
  • No R8/ProGuard rules are needed: the modules use no reflection.