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.
Add dependencies
SSE
only requires the ktor-client-core artifact and doesn't need any specific dependencies.
Install SSE
To install the SSE
plugin, pass it to the install
function inside a client configuration block:
Configure the SSE plugin
You can optionally configure the SSE plugin within the install
block by setting the supported properties of the SSEConfig class:
reconnectionTime
Sets the reconnection delay. If the connection to the server is lost, the client will wait for the specified time before attempting to reconnect.
showCommentEvents()
Adds events that contain only comments in the incoming flow.
showRetryEvents()
Adds events that contain only the
retry
field in the incoming flow.
In the following example, the SSE plugin is installed into the HTTP client and configured to include events that only contain comments and those that contain only the retry
field in the incoming flow:
Handle SSE sessions
A client's SSE session is represented by the DefaultClientSSESession interface. This interface exposes the API that allows you to receive server-sent events from a server.
Access an SSE session
The HttpClient
allows you to get access to an SSE session in one of the following ways:
The sse() function creates the SSE session and allows you to act on it.
The sseSession() function allows you to open an SSE session.
The following parameters are available to both functions. To specify the URL endpoint, choose from two options:
Use the
urlString
parameter to specify the whole URL as a string.Use the
schema
,host
,port
, andpath
parameters to specify the protocol scheme, domain name, port number and path name respectively.
Optionally, the following parameters are available to configure the connection:
reconnectionTime
Sets the reconnection delay.
showCommentEvents
Specifies whether to show events that contain only comments in the incoming flow.
showRetryEvents
Specifies whether to show events that contain only the
retry
field in the incoming flow.
SSE session block
Within the lambda argument, you have access to the ClientSSESession
context. The following properties are available within the block:
call
The associated
HttpClientCall
that originated the session.incoming
An incoming server-sent events flow.
Example
The example below creates a new SSE session with the events
endpoint, reads events through the incoming
property and prints the received ServerSentEvent
.
For the full example, see client-sse.