Java / Gradle

Expose a WebSocket Server in a Micronaut Application

Build a chat application by exposing a WebSocket Server with the Micronaut Framework

Dan Hollingsworth, Sergio del Amo
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Java.

The WebSocket Protocol allows for web browsers to establish interactive sessions with a server that are event-driven. This technology is ideal for applications that need state changes without the overhead and latency of polling the server. The article "Introduction to WebSockets" explains the benefits of WebSocket in more depth, along with a discussion of the client-side WebSocket API.

This guide will take you through the creation of an event-driven chat application utilizing Micronaut WebSocket.

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=websocket,validation,reactor,awaitility,graalvm \
    --build=gradle \
    --lang=java \
    --test=junit
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add websocket, validation, reactor, awaitility, and graalvm features.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

Static Resources

Update application.properties to add static resource configuration:

src/main/resources/application.properties

Front End

HTML

Add the HTML page to be the user interface for the chat client in the browser:

src/main/resources/public/index.html
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>WebSocket Demo</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div id="chatControls">
    <input id="message" placeholder="Type your message">
    <button id="send">Send</button>
</div>
<ul id="userlist"> <!-- Built by JS --> </ul>
<div id="chat">    <!-- Built by JS --> </div>
<script src="websocketDemo.js"></script>
</body>
</html>

Javascript

Write JavaScript to parse the URL for the chat topic and username, handle the message body, broadcast the chat, and keep the DOM updated with the latest messages:

src/main/resources/public/websocketDemo.js
//Establish the WebSocket connection and set up event handlers
var hash = document.location.hash.split("/");

if (hash.length !== 3) {
    alert("Specify URI with a topic and username. "
    + "Example http://localhost:8080#/stuff/bob")
}

var webSocket = new WebSocket("ws://" +
    location.hostname +
    ":" +
    location.port +
    "/ws/chat/" +
    hash[1] +
    "/" +
    hash[2]);
webSocket.onmessage = function (msg) { updateChat(msg); };
webSocket.onclose = function () { alert("WebSocket connection closed") };

//Send message if "Send" is clicked
id("send").addEventListener("click", function () {
    sendMessage(id("message").value);
});

//Send message if enter is pressed in the input field
id("message").addEventListener("keypress", function (e) {
    if (e.keyCode === 13) { sendMessage(e.target.value); }
});

//Send a message if it's not empty, then clear the input field
function sendMessage(message) {
    if (message !== "") {
        webSocket.send(message);
        id("message").value = "";
    }
}

//Update the chat-panel, and the list of connected users
function updateChat(msg) {
    insert("chat", msg.data);
}

//Helper function for inserting HTML as the first child of an element
function insert(targetId, message) {
    id(targetId).insertAdjacentHTML("afterbegin", "<p>" + message + "</p>");
}

//Helper function for selecting element by id
function id(id) {
    return document.getElementById(id);
}

CSS

Style the page so that the messages are properly displayed:

src/main/resources/public/style.css
* {
    box-sizing: border-box;
}

html {
    overflow-y: scroll;
}

body {
    font-family: monospace;
    font-size: 14px;
    max-width: 480px;
    margin: 0 auto;
    padding: 20px;
}

input {
    width: 100%;
    padding: 5px;
    margin: 5px 0;
}

button {
    float: right;
}

li {
    margin: 5px 0;
}

#chatControls {
    overflow: auto;
    margin: 0 0 5px 0;
}

#userlist {
    position: fixed;
    left: 50%;
    list-style: none;
    margin-left: 250px;
    background: #f0f0f9;
    padding: 5px 10px;
    width: 150px;
    top: 11px;
}

#chat p {
    margin: 5px 0;
    font-weight: 300;
}

#chat .timestamp {
    position: absolute;
    top: 10px;
    right: 10px;
    font-size: 12px;
}

#chat article {
    background: #f1f1f1;
    padding: 10px;
    margin: 10px 0;
    border-left: 5px solid #aaa;
    position: relative;
    word-wrap: break-word;
}

#chat article:first-of-type {
    background: #c9edc3;
    border-left-color: #74a377;
    animation: enter .2s 1;
}

@keyframes enter {
    from { transform: none;        }
    50%  { transform: scale(1.05); }
    to   { transform: none;        }
}

Chat server

Our chat server is very simple. It merely allows you to connect and broadcast messages to subscribers of the topic. There’s also a special topic called "all" that can make announcements and receive messages from all topics.

java/src/main/java/example/micronaut/ChatServerWebSocket.java

Test

To test asynchronous code, use Awaitility:

Awaitility is a DSL that allows you to express expectations of an asynchronous system in a concise and easy to read manner.

Micronaut Launch/CLI feature awaitility adds the following dependency:

build.gradle
testImplementation("org.awaitility:awaitility:@awaitilityVersion@")

The Micronaut framework eases the creation of WebSocket servers and clients.

Write a test that uses ClientWebSocket to test the application.

java/src/test/java/example/micronaut/ChatServerWebSocketTest.java

Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

Running the Application

To run the application, use the ./gradlew run command, which starts the application on port 8080.

Open a browser and visit a URL such as http://localhost:8080/#/java/Joe. Then in another browser tab, open http://localhost:8080/\#/java/Moka. You can then try sending chats as Joe and Moka.

Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.

Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.

Note
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

GraalVM Installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 25
sdk install java 25.0.2-graal

For installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 25
sdk install java 25.0.2-graalce

Native Executable Generation

To generate a native executable using Gradle, run:

./gradlew nativeCompile

The native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.

It is possible to customize the name of the native executable or pass additional parameters to GraalVM:

build.gradle

open your browser and visit http://localhost:8080/\#/java/Joe

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).