Right now I’m using KTor as a way to expose websockets to Kotlin I’d like to be able to receive data from a preexisting server while the sketch runs, but Ive had limited success. It seems like theres difficulty in keeping the websocket session open while the sketch runs. My current goal is to print any incoming messages to the command line while the sketch runs. Instead of that, Ive gotten:
- Receive data while the sketch window does not appear
- Receive data while the sketch window appears but is black (seems like the drawer hasnt been initiated yet).
- Receive data and sketch renders, but the websocket connection consistently closes and opens, barraging the server.
- Sketch renders, only receives init data, and the connection seems to immediately close. Sketch proceeds as normal. <— I am here
I have an additional terminal showing the data the server is outputting, so I’m very sure it is not the server. Has anyone successfully done this?
I will post my code a few minutes after post time.
import org.openrndr.application
import org.openrndr.color.ColorRGBa
import org.openrndr.draw.loadFont
import org.openrndr.draw.loadImage
import org.openrndr.draw.tint
import kotlin.math.cos
import kotlin.math.sin
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.websocket.*
import io.ktor.http.*
import io.ktor.websocket.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.ClosedReceiveChannelException
fun main() = application {
configure {
width = 768
height = 576
}
var session: WebSocketSession? = null
val client = HttpClient(CIO) {
install(WebSockets)
}
runBlocking{
client.webSocket(method = HttpMethod.Get,host = "localhost", port=8040,path="/"){
session = this
}
}
program {
val image = loadImage("data/images/pm5544.png")
val font = loadFont("data/fonts/default.otf", 64.0)
extend {
runBlocking {
try{
for(msg in session!!.incoming){
msg as? Frame.Text ?: continue
println(msg.readText())
}
}catch(e:ClosedReceiveChannelException){
}
}
drawer.drawStyle.colorMatrix = tint(ColorRGBa.WHITE.shade(0.2))
drawer.image(image)
drawer.fill = ColorRGBa.PINK
drawer.circle(cos(seconds) * width / 2.0 + width / 2.0, sin(0.5 * seconds) * height / 2.0 + height / 2.0, 140.0)
drawer.fontMap = font
drawer.fill = ColorRGBa.WHITE
drawer.text("OPENRNDR", width / 2.0, height / 2.0)
}
}
}
added to gradle file
implementation("io.ktor:ktor-client-core:2.2.4")
implementation("io.ktor:ktor-client-cio:2.2.4")
implementation("io.ktor:ktor-client-logging:2.2.4")
implementation("io.ktor:ktor-client-websockets:2.2.4")