WebSockets ( Sep 22, 2017 )

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

Functional WebSockets

There is only one change in this release, but it’s a big one. Version 0.5.1 introduces a WebSocket API, built on top of Jetty.

WebSockets can be enabled in three different ways:

Lambda approach

Java

Kotlin app . ws ( "/websocket" , ws -> { ws . onConnect ( session -> System . out . println ( "Connected" )); ws . onMessage (( session , message ) -> { System . out . println ( "Received: " + message ); session . getRemote (). sendString ( "Echo: " + message ); }); ws . onClose (( session , statusCode , reason ) -> System . out . println ( "Closed" )); ws . onError (( session , throwable ) -> System . out . println ( "Errored" )); }); app . ws ( "/websocket" ) { ws -> ws . onConnect { session -> println ( "Connected" ) } ws . onMessage { session , message -> println ( "Received: " + message ) session . remote . sendString ( "Echo: " + message ) } ws . onClose { session , statusCode , reason -> println ( "Closed" ) } ws . onError { session , throwable -> println ( "Errored" ) } }

Annotated class

You can pass an annotated class to the ws() function:

app . ws ( "/websocket" , WebSocketClass . class );

Annotation API can be found on Jetty’s docs page

WebSocket object

You can pass any object that fulfills Jetty’s requirements (annotated/implementing WebSocketListener , etc):