Ktor 3.0.0-rc-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

API overview

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:

routing { sse("/events") { //send events to clients } }

It is also possible to define an SSE route without specifying a path:

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

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:

  • Use the send() function to create and send a ServerSentEvent to the client.

  • Use the call property to access the associated received ApplicationCall that originated the session.

  • Use the close() function to close the session and terminate the connection with the client. The close() method is called automatically when all send() operations are completed.

Example: Handle a single session

The example below creates an SSE session with the events endpoint which sends 6 separate events over a single SSE channel with a delay of 1000ms.

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

For the full example, see server-sse.

Last modified: 30 April 2024