Important: This news article covers an old version of Javalin (v0.5.1).
The current version is v6.3.0.
See the documentation page for up-to-date information.
See the documentation page for up-to-date information.
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):
app.ws("/websocket", new WebSocketObject());