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:
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 theApplication
class.
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:
With a specific URL path:
routing { sse("/events") { // send events to clients } }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 allsend()
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:
For the full example, see server-sse.