Ktor 3.0.1 Help

Server-Sent Events

Server-Sent Events (SSE) is a technology that allows a server to continuously push events to a client over an HTTP connection. It's particularly useful in cases where the server needs to send event-based updates without requiring the client to repeatedly poll the server.

The SSE plugins supported by Ktor provide a straightforward method for creating a one-way connection between the server and the client.

Limitations

Ktor does not provide support for data compression of SSE responses. If you use the Compression plugin, it will skip compression for SSE responses by default.

Add dependencies

To use SSE, you need to include the ktor-server-sse artifact in the build script:

implementation("io.ktor:ktor-server-sse:$ktor_version")
implementation "io.ktor:ktor-server-sse:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-sse-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install SSE

To install the SSE plugin to the application, pass it to the install function in the specified module. The code snippets below show how to install SSE...

  • ... inside the embeddedServer function call.

  • ... inside the explicitly defined module, which is an extension function of the Application class.

import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.application.* import io.ktor.server.sse.* fun main() { embeddedServer(Netty, port = 8080) { install(SSE) // ... }.start(wait = true) }
import io.ktor.server.application.* import io.ktor.server.sse.* // ... fun Application.module() { install(SSE) // ... }

Handle SSE sessions

Once you have installed the SSE plugin, you can add a route to handle an SSE session. To do that, call the sse() function inside the routing block. There are two ways to set up an SSE route:

  1. With a specific URL path:

    routing { sse("/events") { // send events to clients } }
  2. Without a path:

    routing { sse { // send events to clients } }

SSE session block

Within the sse block, you define the handler for the specified path, represented by the ServerSSESession class. The following functions and properties are available within the block:

send()

Creates and sends a ServerSentEvent to the client.

call

The associated received ApplicationCall that originated the session.

close()

Closes the session and terminates the connection with the client. The close() method is called automatically when all send() operations are completed.

Example: Handling a single session

The example below demonstrates how to set up an SSE session on the /events endpoint, sending 6 separate events over the SSE channel with a 1-second (1000ms) delay between each:

routing { sse("/events") { repeat(6) { send(ServerSentEvent("this is SSE #$it")) delay(1000) } } }

For the full example, see server-sse.

Last modified: 15 October 2024