Skip to content

Instantly share code, notes, and snippets.

@Nullable-TB
Created June 2, 2020 01:38
Show Gist options
  • Save Nullable-TB/258783dcfef4521fb32715254562286e to your computer and use it in GitHub Desktop.
Save Nullable-TB/258783dcfef4521fb32715254562286e to your computer and use it in GitHub Desktop.
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import io.ktor.application.install
import io.ktor.features.CallLogging
import io.ktor.features.ContentNegotiation
import io.ktor.features.DefaultHeaders
import io.ktor.gson.gson
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import io.ktor.http.cio.websocket.send
import io.ktor.routing.routing
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.websocket.WebSockets
import io.ktor.websocket.webSocket
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.delay
/*
* This server example requires Kotlin, GSON, KTor, and Kotlin coroutines (which is included in KTor)
*/
val gson = Gson()
fun main() {
embeddedServer(Netty, 8374) {
install(DefaultHeaders)
install(CallLogging)
/**
* Install Websocket
*/
install(WebSockets)
install(ContentNegotiation) {
gson {}
}
routing {
webSocket("/") {
// This will execute when something connects to the websocket server
println("Tribot process connected...")
delay(10000) // This is the part where you open up a tab or two
// Send a message
val request = RpcRequest("2.0", "1", "getTabs", JsonArray())
send(gson.toJson(request))
try {
while (true) {
when (val frame = incoming.receive()) {
is Frame.Text -> {
val text = frame.readText()
println("Received Response:")
println(text)
}
else -> println("Got something but I don't know what it is")
}
}
}
catch (e: ClosedReceiveChannelException) {
println("onClose ${closeReason.await()}")
}
catch (e: Throwable) {
println("onError ${closeReason.await()}")
e.printStackTrace()
}
}
}
}.start(wait = true)
}
data class RpcRequest(val jsonrpc: String = "2.0", val id: String?, val method: String, val params: JsonElement?)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment