Get started · JVM

JVM servers and desktop

The JVM is where kcoap is tested most: every common test, real sockets, and the live interop with libcoap and libedhoc. This guide sets up a Kotlin/JVM application and runs a first server and client.

  • Targetjvm, Java 17 bytecode
  • TransportsUDP, TCP, TLS client, WebSocket client and server
  • CryptographyJCA; Bouncy Castle for post-quantum
  • MinimumJava 17, Kotlin 2.3

Prerequisites

  • A JDK 17 or newer, to build and run your application.
  • Kotlin 2.3 or newer in your project. The samples use 2.4.21, the version kcoap is built with.

Install status

On Maven Central

kcoap 0.1.0 is on Maven Central under dev.kcoap. The build file below takes it from mavenCentral(), which also has every library kcoap depends on.

Set up

  1. Create the build file

    A plain Kotlin/JVM application. Without a toolchain setting it compiles for the JDK that runs Gradle, which must be 17 or newer. The bill of materials, kcoap-bom, sets one version for every kcoap module, so the modules name none.

    Kotlin DSL

    build.gradle.kts

    plugins {
        kotlin("jvm") version "2.4.21"
        application
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation(platform("dev.kcoap:kcoap-bom:0.1.0"))
        implementation("dev.kcoap:kcoap-coap")
        implementation("dev.kcoap:kcoap-transport-ktor")
        implementation("dev.kcoap:kcoap-crypto-default")
        implementation("dev.kcoap:kcoap-oscore")
        implementation("dev.kcoap:kcoap-edhoc-oscore")
        testImplementation("dev.kcoap:kcoap-testkit")
    }
    
    application {
        mainClass = "MainKt"
    }

    Version catalog

    gradle/libs.versions.toml

    [versions]
    kotlin = "2.4.21"
    kcoap = "0.1.0"
    
    [libraries]
    kcoap-bom = { module = "dev.kcoap:kcoap-bom", version.ref = "kcoap" }
    kcoap-coap = { module = "dev.kcoap:kcoap-coap" }
    kcoap-transport-ktor = { module = "dev.kcoap:kcoap-transport-ktor" }
    kcoap-crypto-default = { module = "dev.kcoap:kcoap-crypto-default" }
    kcoap-oscore = { module = "dev.kcoap:kcoap-oscore" }
    kcoap-edhoc-oscore = { module = "dev.kcoap:kcoap-edhoc-oscore" }
    kcoap-testkit = { module = "dev.kcoap:kcoap-testkit" }
    
    [bundles]
    kcoap = [
        "kcoap-coap",
        "kcoap-transport-ktor",
        "kcoap-crypto-default",
        "kcoap-oscore",
        "kcoap-edhoc-oscore",
    ]
    
    [plugins]
    kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }

    build.gradle.kts

    plugins {
        alias(libs.plugins.kotlin.jvm)
        application
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation(platform(libs.kcoap.bom))
        implementation(libs.bundles.kcoap)
        testImplementation(libs.kcoap.testkit)
    }
    
    application {
        mainClass = "MainKt"
    }
  2. Add what else you need

    ForAdd
    WebSocket clientdev.kcoap:kcoap-transport-ktor-websocket
    WebSocket serverdev.kcoap:kcoap-transport-ktor-websocket-server and a ktor server engine, such as io.ktor:ktor-server-cio:3.6.1, the ktor version kcoap is built with
    Post-quantum EDHOCdev.kcoap:kcoap-crypto-bc (ML-KEM and ML-DSA on Bouncy Castle 1.86), next to kcoap-crypto-default
    Tests on virtual timedev.kcoap:kcoap-testkit and org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0

First client and server

A server with two resources on UDP port 5683 of the loopback interface, and a client in the same process that reads one, writes the other and reads it back. Requests are suspend functions; scope owns the coroutines of both.

src/main/kotlin/Main.kt

import dev.kcoap.coap.CoapResponse
import dev.kcoap.coap.ContentFormat
import dev.kcoap.coap.client.CoapClient
import dev.kcoap.coap.server.CoapServer
import dev.kcoap.transport.ktor.KtorUdpTransport
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.runBlocking

fun main() = runBlocking(Dispatchers.IO) {
    val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    try {
        var stored = "nothing yet"
        val transport = KtorUdpTransport.bind("127.0.0.1", 5683)
        val server = CoapServer(transport, scope) {
            resource("hello") { get { CoapResponse.content("Hello, $peer") } }
            resource("store") {
                get { CoapResponse.content(stored) }
                put {
                    stored = payloadAsText()
                    CoapResponse.changed()
                }
            }
        }

        val client = CoapClient(KtorUdpTransport.bind("127.0.0.1"), scope)
        val uri = "coap://127.0.0.1:5683"
        println(client.get("$uri/hello").payloadAsText())
        val body = "on".encodeToByteArray()
        client.put("$uri/store", body, ContentFormat.TEXT_PLAIN)
        println(client.get("$uri/store").payloadAsText())

        client.close()
        server.close()
    } finally {
        scope.cancel()
    }
}

The server and client lines, with two long ones split, are those of the client and server guide, which GuideExamplesTest compiles and runs in CI. The main function around them is not compiled there.

Run it with ./gradlew run. The client binds port 0, so the system picks a free port, and the server greets it by its address:

Output

Hello, Udp(host=127.0.0.1, port=51234)
on

Over TCP and WebSockets

The same server can listen on TCP (coap+tcp) and WebSockets (coap+ws) instead of UDP. Add kcoap-transport-ktor-websocket, kcoap-transport-ktor-websocket-server and io.ktor:ktor-server-cio:3.6.1; the WebSocket listener serves the path /.well-known/coap with the subprotocol coap.

src/main/kotlin/Reliable.kt

import dev.kcoap.coap.CoapResponse
import dev.kcoap.coap.client.CoapClient
import dev.kcoap.coap.server.CoapServer
import dev.kcoap.transport.ktor.KtorTcpConnector
import dev.kcoap.transport.ktor.KtorTcpListener
import dev.kcoap.transport.ktor.websocket.KtorWebSocketConnector
import dev.kcoap.transport.ktor.websocket.server.KtorWebSocketListener
import io.ktor.server.cio.CIO
import kotlinx.coroutines.CoroutineScope

suspend fun reliableServer(
    scope: CoroutineScope,
    tcpPort: Int,
    webSocketPort: Int,
): CoapServer {
    val listeners = listOf(
        // coap+tcp
        KtorTcpListener.bind("127.0.0.1", tcpPort),
        // coap+ws, at /.well-known/coap
        KtorWebSocketListener.start(CIO, "127.0.0.1", webSocketPort),
    )
    return CoapServer(listeners, scope) {
        resource("hello") {
            get { CoapResponse.content("Hello over ${peer::class.simpleName}") }
        }
    }
}

suspend fun reliableClient(
    scope: CoroutineScope,
    tcpPort: Int,
    webSocketPort: Int,
) {
    val connectors = listOf(KtorTcpConnector(), KtorWebSocketConnector())
    val client = CoapClient(connectors, scope)
    val tcp = "coap+tcp://127.0.0.1:$tcpPort"
    val webSocket = "coap+ws://127.0.0.1:$webSocketPort"
    // Prints "Hello over Tcp", "Hello over WebSocket" and "true"
    println(client.get("$tcp/hello").payloadAsText())
    println(client.get("$webSocket/hello").payloadAsText())
    println(client.ping(tcp))
    client.close()
}

The code of GuideExamplesTest.theTcpAndWebSocketExamplesWork, which compiles and runs it in CI and checks the three lines of output; here its long lines are split, with the URIs in variables.

To serve CoAP from a ktor application you already run, mount the listener instead: create KtorWebSocketListener(), install ktor’s WebSockets without a ping period, and add routing { coapOverWebSockets(listener) }.

A test without a network

kcoap-testkit runs a server and a client on an in-memory network that loses and duplicates datagrams, on the test’s virtual time, so a test of a 93-second give-up takes milliseconds.

src/test/kotlin/GreetingTest.kt

import dev.kcoap.coap.CoapResponse
import dev.kcoap.coap.client.CoapClient
import dev.kcoap.coap.server.CoapServer
import dev.kcoap.coap.stack.CoapEndpointConfig
import dev.kcoap.testkit.InMemoryNetwork
import dev.kcoap.testkit.LinkConditions
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.test.runTest

class GreetingTest {
    @Test
    fun greets() = runTest {
        val network = InMemoryNetwork(backgroundScope, Random(1))
        network.conditions =
            LinkConditions(lossRate = 0.3, duplicationRate = 0.1)
        val config = CoapEndpointConfig {
            timeSource = testScheduler.timeSource
        }
        val serverTransport = network.attach()
        CoapServer(serverTransport, backgroundScope, endpointConfig = config) {
            resource("hello") { get { CoapResponse.content("Hello") } }
        }
        val client = CoapClient(
            network.attach(), backgroundScope, endpointConfig = config,
        )
        val address = serverTransport.localEndpoint
        val reply = client.get("coap://${address.host}:${address.port}/hello")
        assertEquals("Hello", reply.payloadAsText())
    }
}

The test is GuideExamplesTest.greets, which runs in CI, with its lines wrapped and its last assertion split in two here. It needs kotlinx-coroutines-test and kotlin("test") as test dependencies.

Securing it

OSCORE and EDHOC work the same on every platform; the quick start shows an OSCORE server and client, then EDHOC with the combined request, two round trips in all. On a JVM server, three things matter more than elsewhere:

  • Sequence numbers must survive restarts. Pre-shared OSCORE keys need a durable SequenceNumberStore; kcoap ships none on purpose. The JVM recipe writes a temporary file, forces it to disk and moves it into place.
  • Bound the contexts. InMemoryContextRepository never evicts. A production server that runs EDHOC supplies a bounded MutableSecurityContextRepository.
  • Post-quantum EDHOC runs here. BouncyCastleCryptoBackend(DefaultCryptoBackend()) from kcoap-crypto-bc adds ML-KEM and ML-DSA to the classical backend you pass, here the one of kcoap-crypto-default; configure CipherSuite.SUITE_PQC_1 (suite −24). What is verified.

Platform notes

Transports

KtorUdpTransport (coap), KtorTcpConnector and KtorTcpListener (coap+tcp) run on ktor-network’s NIO sockets. KtorWebSocketConnector uses the CIO client engine by default. KtorWebSocketListener brings no server engine: you pass one, and CIO is the one kcoap’s tests use. CI tests UDP and TCP on real sockets, over IPv4 and IPv6 loopback.

TLS

KtorTlsConnector opens coaps+tcp connections on ktor-network-tls. It checks the server’s chain against the JDK’s trust store, or trust anchors you give in TlsClientConfig, checks that the certificate names the host, and takes a pinning hook. It speaks TLS 1.2 without ALPN, so a port other than 5684 needs allowsAnyPortWithoutAlpn. For coaps+ws, pass KtorWebSocketConnector an HttpClient whose engine checks host names: the default CIO client does not list coaps+ws on the JVM.

Tls.kt

// coaps+tcp to port 5684; the server's chain is checked against
// the JDK's trust store and must name coap.example.org
val client = CoapClient(listOf(KtorTlsConnector()), scope)
println(client.get("coaps+tcp://coap.example.org/sensors/temp").payloadAsText())

From the KDoc of KtorTlsConnector; names checked. KcoapClientAgainstLibcoapTlsTest runs the connector against libcoap in CI.

kcoap has no TLS listener: a server terminates TLS at a reverse proxy, such as HAProxy or nginx’s stream module, in front of KtorTcpListener (ADR 0010).

Cryptography

DefaultCryptoBackend() uses the JDK’s own providers through JCA. The JVM runs every EDHOC suite kcoap implements; suites 0, 2, 4 and 24 and the post-quantum suite −24 are cross-tested against libedhoc here.

Not done yet on the JVM

  • TLS 1.3, ALPN and a TLS listener: the client speaks TLS 1.2 only, and servers terminate TLS at a reverse proxy. DTLS for coaps:// comes last.
  • No benchmarks, no metrics adapter, no Java-friendly facade and no server guide yet. Each endpoint has one socket and one lock.

Troubleshooting

Could not find dev.kcoap:kcoap-coap:0.1.0
Check that mavenCentral() is in your repositories, or in dependencyResolutionManagement when the settings file declares them.
An error about inlining bytecode built with JVM target 17
Your project compiles for an older JVM. Build it with a JDK 17 or newer, or set the Kotlin jvmTarget to 17 or newer.
Cannot resolve '…': configure an EndpointResolver
The default resolver turns IP addresses and localhost into coap:// endpoints but knows no DNS. Use an IP address, or set CoapClientConfig { resolver = EndpointResolver { … } }. TCP and WebSocket connectors resolve host names themselves.
The server cannot bind port 5683
Another CoAP server, such as libcoap’s coap-server, has it. Pick another port, or pass 0 and read transport.localEndpoint.port.
The WebSocket listener does not start
Add a ktor server engine, such as io.ktor:ktor-server-cio:3.6.1. kcoap’s WebSocket server module brings none on purpose.

Next steps