Real-time chat applications are essential in modern web systems, enabling seamless communication between users. The Jakarta WebSocket API offers an elegant way to build such applications, leveraging Java’s robust capabilities. Combined with Open Liberty, a lightweight and flexible Java runtime, you can create high-performance chat apps efficiently. This article will walk you through building a real-time chat app using Jakarta WebSocket and Open Liberty, complete with code examples and a comprehensive explanation.

Prerequisites

Before diving into the implementation, ensure you have the following set up:

  • Java Development Kit (JDK): Version 11 or higher.
  • Maven: For managing project dependencies.
  • Open Liberty Runtime: Downloadable from Open Liberty’s official site.
  • An IDE: IntelliJ IDEA, Eclipse, or Visual Studio Code.

Setting Up the Open Liberty Project

  1. Create a Maven Project: Use Maven to create a new project:
    bash
    mvn archetype:generate \
    -DgroupId=com.example \
    -DartifactId=chat-app \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DinteractiveMode=false
  2. Add Dependencies: Add Jakarta WebSocket and Open Liberty dependencies in your pom.xml:
    xml
    <dependencies>
    <dependency>
    <groupId>jakarta.websocket</groupId>
    <artifactId>jakarta.websocket-api</artifactId>
    <version>2.1.0</version>
    </dependency>
    <dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-web-api</artifactId>
    <version>10.0.0</version>
    <scope>provided</scope>
    </dependency>
    </dependencies>
  3. Configure Open Liberty: Add the Open Liberty plugin and server configuration to pom.xml:
    xml
    <build>
    <plugins>
    <plugin>
    <groupId>io.openliberty.tools</groupId>
    <artifactId>liberty-maven-plugin</artifactId>
    <version>3.6</version>
    </plugin>
    </plugins>
    </build>

    Create a server.xml file in the src/main/liberty/config directory with the following content:

    xml
    <server>
    <featureManager>
    <feature>websocket-1.1</feature>
    <feature>servlet-4.0</feature>
    </featureManager>
    <httpEndpoint host="*" httpPort="9080" />
    </server>

Implementing the WebSocket Endpoint

  1. Create a WebSocket Server Endpoint: Define a class annotated with @ServerEndpoint to handle WebSocket connections:
    java

    package com.example.chat;

    import jakarta.websocket.OnClose;
    import jakarta.websocket.OnMessage;
    import jakarta.websocket.OnOpen;
    import jakarta.websocket.Session;
    import jakarta.websocket.server.ServerEndpoint;
    import java.util.Set;
    import java.util.concurrent.CopyOnWriteArraySet;

    @ServerEndpoint(“/chat”)
    public class ChatEndpoint {
    private static final Set<Session> sessions = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session) {
    sessions.add(session);
    System.out.println(“New connection: “ + session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
    for (Session s : sessions) {
    if (s.isOpen()) {
    s.getAsyncRemote().sendText(message);
    }
    }
    }

    @OnClose
    public void onClose(Session session) {
    sessions.remove(session);
    System.out.println(“Connection closed: “ + session.getId());
    }
    }

  2. Deploy the Endpoint: Place the WebSocket class in the src/main/java directory and package your application using Maven:
    bash
    mvn package

    Deploy the .war file to Open Liberty by running:

    bash
    mvn liberty:run

Building the Front-End Chat Interface

To interact with the WebSocket server, create a simple HTML/JavaScript interface.

  1. HTML Structure: Create an index.html file in the src/main/webapp directory:
    html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat App</title>
    <style>
    body {
    font-family: Arial, sans-serif;
    margin: 20px;
    }
    #chat {
    border: 1px solid #ccc;
    padding: 10px;
    height: 300px;
    overflow-y: scroll;
    }
    #message {
    width: calc(100% - 110px);
    }
    </style>
    </head>
    <body>
    <h1>Real-Time Chat App</h1>
    <div id="chat"></div>
    <input type="text" id="message" placeholder="Type a message...">
    <button onclick="sendMessage()">Send</button>
    <script>
    const chat = document.getElementById(‘chat’);
    const messageInput = document.getElementById(‘message’);
    const ws = new WebSocket(‘ws://localhost:9080/chat-app/chat’);
    ws.onmessage = (event) => {
    const msg = document.createElement(‘div’);
    msg.textContent = event.data;
    chat.appendChild(msg);
    chat.scrollTop = chat.scrollHeight;
    };function sendMessage() {
    const message = messageInput.value;
    if (message.trim() !== ) {
    ws.send(message);
    messageInput.value = ;
    }
    }
    </script>
    </body>
    </html>
  2. Test the Application: Open http://localhost:9080/chat-app/ in multiple browser tabs and exchange messages in real time.

Enhancing the Chat App

Once the basic functionality is in place, consider adding advanced features:

  • Authentication: Require users to log in before joining the chat.
  • Rooms: Allow users to create and join specific chat rooms.
  • Persistence: Save chat history to a database using Jakarta Persistence (JPA).
  • Styling: Improve the UI using CSS frameworks like Bootstrap.

Conclusion

Building a real-time chat application using Jakarta WebSocket and Open Liberty demonstrates the power and flexibility of modern Java frameworks. Jakarta WebSocket simplifies WebSocket-based communication, while Open Liberty provides a lightweight, developer-friendly runtime environment. This combination enables developers to create scalable and responsive applications efficiently.

The example presented here is a starting point, offering core functionalities like message broadcasting and user session management. By extending the application with features like user authentication, chat room management, and database integration, you can create a production-ready solution.

As businesses and users increasingly demand real-time communication solutions, mastering tools like Jakarta WebSocket and Open Liberty will position you to deliver innovative, high-quality applications. Whether you are a seasoned developer or just starting, this tech stack empowers you to meet modern application requirements effectively.