Server-sent events support! ( Jan 17, 2019 )

What's Javalin? Javalin is a very lightweight Java and Kotlin web framework which focuses on simplicity and Java/Kotlin interoperability. Read more on our landing page

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