asJsonRpcConnection
suspend fun Pair<ByteReadChannel, ByteWriteChannel>.asJsonRpcConnection(env: KsrpcEnvironment<String>, includeContentHeaders: Boolean = true, cancellationConvention: JsonRpcCancellationConvention = JsonRpcCancellationConvention.None, contextConvention: JsonRpcContextConvention = JsonRpcContextConvention.RootSiblings): SingleChannelConnection<String>
Create a SingleChannelConnection that communicates over this pair of byte channels using JSON-RPC 2.0 framing.
For hosting JSON-RPC over a process' stdin/stdout (e.g. LSP-style protocols on the JVM), see stdInJsonRpcConnection (JVM only), demonstrated in the second sample below.
Samples
import com.monkopedia.ksrpc.channels.connect
import com.monkopedia.ksrpc.jsonrpc.asJsonRpcConnection
import com.monkopedia.ksrpc.jsonrpc.stdInJsonRpcConnection
import com.monkopedia.ksrpc.ksrpcEnvironment
import com.monkopedia.ksrpc.serialized
import com.monkopedia.ksrpc.toStub
import io.ktor.utils.io.ByteChannel
fun main() {
//sampleStart
val env = ksrpcEnvironment { }
// Any pair of byte read/write channels can be a JSON-RPC connection.
val readChannel = ByteChannel(autoFlush = true)
val writeChannel = ByteChannel(autoFlush = true)
val connection = (readChannel to writeChannel).asJsonRpcConnection(env)
// Register a service on the connection.
val service = object : GreetingService {
override suspend fun greet(name: String): String = "Hello, $name!"
}
connection.registerDefault(service.serialized(env))
//sampleEnd
}import com.monkopedia.ksrpc.channels.connect
import com.monkopedia.ksrpc.jsonrpc.asJsonRpcConnection
import com.monkopedia.ksrpc.jsonrpc.stdInJsonRpcConnection
import com.monkopedia.ksrpc.ksrpcEnvironment
import com.monkopedia.ksrpc.serialized
import com.monkopedia.ksrpc.toStub
import io.ktor.utils.io.ByteChannel
fun main() {
//sampleStart
val env = ksrpcEnvironment { }
// stdInJsonRpcConnection creates a SingleChannelConnection over stdin/stdout
// using JSON-RPC 2.0 framing with Content-Length headers.
val connection = stdInJsonRpcConnection(env)
// Use connect to set up both host and client sides.
connection.connect<GreetingService, GreetingService, String> { remoteService ->
// remoteService is a stub for the remote side's hosted service.
// Return the local service to host on this side.
object : GreetingService {
override suspend fun greet(name: String): String = "Hello from server, $name!"
}
}
//sampleEnd
}suspend fun Pair<InputStream, OutputStream>.asJsonRpcConnection(env: KsrpcEnvironment<String>): SingleChannelConnection<String>
Helper that calls into Pair
suspend fun ProcessBuilder.asJsonRpcConnection(env: KsrpcEnvironment<String>): SingleChannelConnection<String>
Create a SingleChannelConnection that starts the process and uses the Process.getInputStream and Process.getOutputStream as the streams for communication using jsonrpc.