kotlinx.rpc 0.9.1 Help

Ktor

The kotlinx.rpc library provides integration with the Ktor framework. This includes both server and client APIs. Under the hood, the library uses WebSocket plugin to create a KrpcTransport and send and receive messages through it.

Client

kotlinx.rpc provides a way to plug-in into existing Ktor clients with your RPC services. To do that, the following DSL can be used:

val ktorClient = HttpClient { installKrpc { waitForServices = true } } val rpcClient: KtorKrpcClient = ktorClient.rpc("ws://localhost:4242/services") { rpcConfig { waitForServices = false } } // get an RPC service val myService: MyService = rpcClient.withService<MyService>()

Server

kotlinx.rpc provides a way to plug-in into existing server routing with your RPC services. To do that, the following DSL can be used:

fun Application.module() { install(Krpc) { waitForServices = true } routing { rpc("/services") { rpcConfig { waitForServices = false } registerService<MyService> { MyServiceImpl() } registerService<MyOtherService> { MyOtherServiceImpl() } // more services if needed } } }

Ktor application example

An example code for a Ktor web application may look like this:

In common code, shared classes and services are defined:

@Serializable data class ProcessedImage( val url: String, val numberOfCats: Int, val numberOfDogs: Int ) @Rpc interface ImageService { suspend fun processImage(url: String): ProcessedImage }

In client code, create an HTTP client and access the service on a the desired route:

val client = HttpClient { installKrpc { serialization { json() } } } val service = client .rpc("/image-recognizer") .withService<ImageService>() service.processImage(url = "https://catsanddogs.com/cats/1")

In server code, provide an implementation of the ImageService and register it on a route:

class ImageServiceImpl : ImageService { // some user defined classes private val downloader = Downloader() private val recognizer = AnimalRecognizer() override suspend fun processImage(url: Srting): ProcessedImage { val image = downloader.loadImage(url) return ProcessedImage( url, recognizer.getNumberOfCatsOnImage(image), recognizer.getNumberOfDogsOnImage(image) ) } } fun main() { embeddedServer(Netty, port = 8080) { install(Krpc) { serialization { json() } } routing { rpc("/image-recognizer") { registerService<ImageService> { ImageServiceImpl() } } } }.start(wait = true) }

For more details and complete examples, see the code samples.

Last modified: 25 June 2025