Search code examples
javascriptkotlinserver-sent-eventsktor

How to write Sse events in Ktor


I'm getting a post request to download something, I need to send download process to client, currently I'm trying to use Server Sent Events for this and EventSource, but it is not working.

My client JS

const result = document.getElementById("result");
const es = new EventSource("/download/process");
es.onmessage = function (event) {
const data = event.data;
console.log("Displaying:" + data);

if (result.innerText.length === 0) {
    result.innerText = data;
} else {
    result.innerText = result.innerText + "\n" + data;
}
    result.scrollTop = result.scrollHeight;
}

Server

val flo = MutableSharedFlow<String>()

routing {
    route("download") {
        get("process") {
            call.response.cacheControl(CacheControl.NoCache(null))
            call.respondBytesWriter(ContentType.Text.EventStream) {
                flo.collect {
                    writeStringUtf8(it)
                    flush()
                }
            }
        }
        post("start") {
            // Get parameters here
            runBlocking {
                // Perform download and send to client event throughout
                flo.tryEmit(it)
            }
            call.respondText("Download finished")
        }
    }
}

Solution

  • @aleksei-tirman answer solved it. I added maven("https://maven.pkg.jetbrains.space/public/p/ktor/eap") to repositories in my Gradle build file, and started using ktor version 3.0.0-eap-800. The SSE plugin is io.ktor:ktor-server-sse-jvm:3.0.0-eap-800.