Server-sent events

Server-sent events has been requested a lot in Javalin, and thanks to two contributors (@7agustibm and @firxworx), we now have an implementation. As with most Javalin APIs, the syntax is lambda based:

val clients = ConcurrentLinkedQueue<SseClient>()

app.sse("/sse") { client ->
    clients.add(client)
    client.sendEvent("connected", "Hello, SSE")
    client.onClose { clients.remove(client) }
}

while (true) {
    for (client in clients) {
        client.sendEvent("PING")
    }
    Thread.sleep(1000)
}

A corresponding JavaScript client would look something like:

const eventSource = new EventSource("http://localhost:7000/sse");
eventSource.addEventListener("connected", msg => console.log(msg);

Server-sent events is also known as “EventSource”, and is useful for when you need to push events to clients (to avoid polling).

Misc

  • Fixed a bug introduced in 2.5.0 which made “catch-all” exception-mappers interfere with HttpResponseException exceptions
  • Added method for retrieving the request context path from Context
  • Javalin#addHandler is now public, this is the internal method that get/post/put/etc call
  • Bumped Jetty