Expose a WebSocket Server in a Micronaut Application
Build a chat application by exposing a WebSocket Server with the Micronaut Framework
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Groovy.
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:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately
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.
-
Download and unzip the source
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 \
--build=maven \
--lang=groovy \
--test=spock|
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, and reactor 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:
|
Warning
|
Since Micronaut Framework 4.0, to use YAML configuration, you have to add the YAML dependency. |
Front End
HTML
Add the HTML page to be the user interface for the chat client in the browser:
<!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:
//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:
* {
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.
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:
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>@awaitilityVersion@</version>
<scope>test</scope>
</dependency>The Micronaut framework eases the creation of WebSocket servers and clients.
Write a test that uses ClientWebSocket to test the application.
Testing the Application
To run the tests:
./mvnw testRunning the Application
To run the application, use the ./mvnw mn: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.
Next Steps
Read more about:
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). |