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
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:
It is also possible to define an SSE route without specifying a path:
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 aServerSentEvent
to the client.Use the
call
property to access the associated receivedApplicationCall
that originated the session.Use the
close()
function to close the session and terminate the connection with the client. Theclose()
method is called automatically when allsend()
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.
For the full example, see server-sse.