Skip to content

Latest commit

 

History

History
117 lines (98 loc) · 2.82 KB

File metadata and controls

117 lines (98 loc) · 2.82 KB

Server-Sent Events

Server-Sent Events (SSE) is a mechanism that allows the server to push data to the client once a connection is established. Unlike WebSockets, SSE is strictly unidirectional: the server can send data to the client, but not the other way around.

Server-Sent Events
{
  sse("/sse", sse -> {            // (1)
    sse.send("Welcome");          // (2)
  });
}
Kotlin
{
  sse("/sse") {                   // (1)
    sse.send("Welcome")           // (2)
  }
}
  1. Connection established.

  2. Send a message to the client.

Message Options

Additional message properties (like custom events, IDs, and retry timeouts) are available via the javadoc:ServerSentMessage[] class:

Server-Sent Message
{
  sse("/sse", sse -> {
    sse.send(
        new ServerSentMessage("...")
            .setEvent("myevent")
            .setId("myId")
            .setRetry(1000)
    );
  });
}
Kotlin
{
  sse("/sse") {
    sse.send(ServerSentMessage("...").apply {
        event = "myevent"
        id = "myId"
        retry = 1000
    })
  }
}

For details on how these options are interpreted by the browser, see the MDN documentation on the Event stream format.

Connection Lost

The sse.onClose(Runnable) callback allows you to clean up and release resources when the connection ends. A connection is considered closed when you explicitly call sse.close() or when the remote client disconnects.

Connection Lost
{
  sse("/sse", sse -> {
    sse.onClose(() -> {
      // Clean up resources
    });
  });
}
Kotlin
{
  sse("/sse") {
    sse.onClose {
      // Clean up resources
    }
  }
}

Keep Alive

You can use the keep-alive feature to prevent idle connections from timing out or being dropped by intermediate proxies:

Keep Alive
{
  sse("/sse", sse -> {
    sse.keepAlive(15, TimeUnit.SECONDS);
  });
}
Kotlin
{
  sse("/sse") {
    sse.keepAlive(15, TimeUnit.SECONDS)
  }
}

This example sends a : message (an empty SSE comment) every 15 seconds to keep the connection active. If the client drops the connection, the sse.onClose event will be fired.

This feature is especially useful for quickly detecting closed connections without having to wait until your application tries to send a real event. (However, if your application already pushes data frequently—e.g., every few seconds—enabling keepAlive is generally unnecessary).