Skip to content
The Chat Archive
grok-3-mini-beta· xAI LMArena Human Preference 140K

Can you use io.quarkus.websockets.next and java to create a chat. And this chat should…

  1. User

    Can you use io.quarkus.websockets.next and java to create a chat. And this chat should be separated into different rooms so not every user get's every message

  2. Assistant

    Sure, I can help you create a simple chat application using Quarkus and Java with WebSocket support. We'll use the Quarkus WebSocket extension, which is based on the standard JSR-356 API (from javax.websocket). The "next" part might refer to Quarkus's evolving WebSocket features, but for this example, I'll use the stable @ServerEndpoint approach, as it's widely supported and straightforward for room-based chat.

    The key requirements are:

    • Users connect via WebSockets.
    • Chats are separated into rooms, so messages are only broadcasted to users in the same room.
    • We'll handle room management on the server side.

    Prerequisites

    1. Set up a Quarkus project: Make sure you have Quarkus installed. You can create a new project with the WebSocket extension using the Quarkus CLI or Maven:

      mvn quarkus:create -DprojectGroupId=org.example -DprojectArtifactId=chat-app -Dextensions="websocket"
      

      This adds the necessary dependencies for WebSockets.

    2. Dependencies: In your pom.xml (for Maven), ensure you have:

      <dependency>
          <groupId>io.quarkus</groupId>
          <artifactId>quarkus-websocket</artifactId>
      </dependency>
      
    3. Run the application: Once implemented, run your Quarkus app with mvn quarkus:dev.

    Step-by-Step Implementation

    We'll create a WebSocket endpoint that:

    • Uses path parameters to specify the room (e.g., /chat/room1).
    • Tracks sessions per room using a concurrent map.
    • Broadcasts messages only to sessions in the same room.

    1. Create the WebSocket Endpoint Class

    Create a new class, e.g., ChatEndpoint.java, in your project's src/main/java directory.

    import javax.websocket.*;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.Collections;
    import java.util.Set;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    @ServerEndpoint("/chat/{room}")  // WebSocket endpoint with a path parameter for the room
    public class ChatEndpoint {
    
        // Map to store rooms: Key is the room name, Value is a set of active sessions in that room
        private static final ConcurrentHashMap<String, Set<Session>> rooms = 
            new ConcurrentHashMap<>();
    
        // Map to track which room each session belongs to (for quick lookups)
        private static final ConcurrentHashMap<Session, String> sessionToRoom = 
            new ConcurrentHashMap<>();
    
        @OnOpen
        public void onOpen(Session session, @PathParam("room") String room) {
            // Add the session to the room's set
            rooms.computeIfAbsent(room, k -> new CopyOnWriteArraySet<>()).add(session);
            sessionToRoom.put(session, room);  // Track the room for this session
            broadcastToRoom(room, "User has joined the room: " + room, session);  // Optional: Notify others
        }
    
        @OnMessage
        public void onMessage(Session session, String message) {
            String room = sessionToRoom.get(session);  // Get the room for this session
            if (room != null) {
                broadcastToRoom(room, message, session);  // Broadcast the message to the room
            } else {
                try {
                    session.getBasicRemote().sendText("Error: You are not in a room.");
                } catch (IOException e) {
                    // Handle error (e.g., log it)
                }
            }
        }
    
        @OnClose
        public void onClose(Session session) {
            String room = sessionToRoom.get(session);
            if (room != null) {
                Set<Session> roomSessions = rooms.get(room);
                if (roomSessions != null) {
                    roomSessions.remove(session);  // Remove the session from the room
                    if (roomSessions.isEmpty()) {
                        rooms.remove(room);  // Clean up if the room is empty
                    }
                    broadcastToRoom(room, "User has left the room: " + room, session);  // Optional: Notify others
                }
                sessionToRoom.remove(session);  // Remove from session tracking
            }
        }
    
        @OnError
        public void onError(Session session, Throwable throwable) {
            System.err.println("WebSocket error: " + throwable.getMessage());
            // You can add more error handling, like closing the session
        }
    
        // Helper method to broadcast messages to a specific room
        private void broadcastToRoom(String room, String message, Session sender) {
            Set<Session> roomSessions = rooms.get(room);
            if (roomSessions != null) {
                for (Session s : roomSessions) {
                    if (s.isOpen() && !s.equals(sender)) {  // Send to others in the room, excluding sender
                        try {
                            s.getBasicRemote().sendText(message);  // Send the message
                        } catch (IOException e) {
                            System.err.println("Error sending message: " + e.getMessage());
                            // Optionally, remove the session if it's no longer valid
                        }
                    }
                }
            }
        }
    }
    

    Explanation of the Code

    • Endpoint Annotation: @ServerEndpoint("/chat/{room}") defines the WebSocket endpoint. Clients connect to URLs like ws://localhost:8080/chat/room1.
    • Room Management:
      • rooms is a ConcurrentHashMap<String, Set<Session>> where the key is the room name, and the value is a set of active WebSocket sessions in that room. We use CopyOnWriteArraySet for thread-safe operations.
      • sessionToRoom is a ConcurrentHashMap<Session, String> to quickly look up which room a session belongs to.
    • Lifecycle Methods:
      • @OnOpen: When a client connects, add their session to the appropriate room and notify others (optional).
      • @OnMessage: When a message is received, get the sender's room and broadcast the message only to sessions in that room.
      • @OnClose: When a client disconnects, remove their session from the room and notify others (optional).
      • @OnError: Handle any errors during the WebSocket connection.
    • Broadcasting: The broadcastToRoom method sends the message to all sessions in the specified room, excluding the sender. This prevents echo-back to the sender.

    How Clients Connect and Interact

    • Client-Side Example: Use a WebSocket client library in JavaScript (for a web app) or any WebSocket client.
      • Connect: new WebSocket("ws://localhost:8080/chat/room1");
      • Send a message: websocket.send("Hello, room!");
      • Receive messages: Listen for onmessage events in the client.

    Example simple HTML/JavaScript client:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Chat App</title>
    </head>
    <body>
        <input type="text" id="messageInput" placeholder="Type a message">
        <button onclick="sendMessage()">Send</button>
        <div id="messages"></div>
    
        <script>
            const room = 'room1';  // Change to desired room
            const websocket = new WebSocket(`ws://localhost:8080/chat/${room}`);
    
            websocket.onopen = () => console.log('Connected to room:', room);
            websocket.onmessage = (event) => {
                document.getElementById('messages').innerHTML += `<p>${event.data}</p>`;
            };
            websocket.onclose = () => console.log('Disconnected');
    
            function sendMessage() {
                const message = document.getElementById('messageInput').value;
                websocket.send(message);
                document.getElementById('messageInput').value = '';  // Clear input
            }
        </script>
    </body>
    </html>
    

    Running and Testing

    1. Build and run the Quarkus app: mvn quarkus:dev.
    2. Open multiple browser tabs with the HTML client above, connecting to the same room (e.g., room1) or different rooms (e.g., room2).
    3. Send messages and verify that they only appear in the same room.

    Limitations and Improvements

    • Security: This is a basic implementation. In a real app, add authentication (e.g., using Quarkus Security) to prevent unauthorized access to rooms.
    • Scalability: The in-memory maps work for small-scale apps, but for production, consider using a distributed cache like Redis for room management across multiple servers.
    • Error Handling: We've added basic error logging; you might want to enhance this with proper logging (e.g., using SLF4J).
    • Quarkus Websockets Next: If you're referring to the reactive WebSocket API (e.g., using Mutiny), Quarkus has experimental support via io.quarkus.vertx.web. Let me know if you want to switch to that—it's more reactive and non-blocking, but the code would look different.

    This should give you a functional room-based chat. If you need any modifications or additional features, just let me know!

  3. User

    switch to use io.quarkus.vertx.web

  4. Assistant

    Sure, I can help you switch to using io.quarkus.vertx.web for your chat application. This approach leverages Quarkus's integration with Vert.x, which provides a reactive, non-blocking API for handling WebSockets. It's more modern and scalable than the JSR-356 based approach we used earlier.

    Key Changes

    • Dependency Update: We'll use the quarkus-vertx-web extension instead of quarkus-websocket. Make sure to add it to your project:

      • If you're using Maven, update your pom.xml:
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-vertx-web</artifactId>
        </dependency>
        
      • Then, rebuild your project with mvn clean install or restart Quarkus dev mode.
    • API Shift: Instead of @ServerEndpoint, we'll define routes using @Route from io.quarkus.vertx.web. This allows us to handle HTTP upgrades to WebSockets and manage the lifecycle (open, message, close) reactively with Mutiny.

    • Room Management: We'll use Vert.x's shared maps (via Vertx.sharedMap()) to track sessions per room, ensuring thread-safety in a reactive context.

    • Reactive Programming: We'll incorporate Mutiny for handling asynchronous operations, which is idiomatic in Quarkus Vert.x applications.

    Step-by-Step Implementation

    Here's how we'll implement the chat application:

    1. Create the Route Handler Class: Create a new class, e.g., VertxChatRoutes.java, in your project's src/main/java directory.

      import io.quarkus.vertx.web.Route;
      import io.quarkus.vertx.web.RouteBase;
      import io.smallrye.mutiny.Multi;
      import io.smallrye.mutiny.Uni;
      import io.vertx.core.Vertx;
      import io.vertx.core.http.ServerWebSocket;
      import io.vertx.ext.web.RoutingContext;
      import io.vertx.mutiny.core.eventbus.EventBus;
      import io.vertx.mutiny.core.shareddata.SharedData;
      import jakarta.inject.Inject;
      import jakarta.ws.rs.Path;
      
      import java.util.Set;
      import java.util.concurrent.ConcurrentHashMap;
      
      @RouteBase(path = "/chat")  // Base path for all routes
      public class VertxChatRoutes {
      
          @Inject
          Vertx vertx;  // Inject Vertx instance
      
          @Inject
          EventBus eventBus;  // Inject EventBus for potential future scalability (not used here)
      
          private static final String SHARED_MAP_NAME = "chatRooms";  // Name of the shared map
      
          @Route(path = "/:room", methods = "GET")  // Route for WebSocket upgrade
          public void handleChat(RoutingContext ctx) {
              if (ctx.request().isWebSocket()) {
                  ctx.request().toWebSocket()
                      .onItem().transformToUni(webSocket -> {
                          String room = ctx.pathParam("room");  // Extract room from path
                          return setupWebSocket(webSocket, room);
                      })
                      .subscribe().with(ignored -> {}, ctx::fail);  // Handle success/failure
              } else {
                  ctx.response().setStatusCode(400).end("WebSocket upgrade required");
              }
          }
      
          private Uni<Void> setupWebSocket(ServerWebSocket webSocket, String room) {
              SharedData sharedData = vertx.sharedData();  // Get shared data
              return sharedData.getMutinyAsyncMap(SHARED_MAP_NAME)  // Get or create the shared map
                  .onItem().transformToUni(asyncMap -> {
                      // asyncMap is a ConcurrentHashMap<String, Set<ServerWebSocket>>
                      return asyncMap.get(room)  // Get the set for the room
                          .onItem().ifNull().continueWith(ConcurrentHashMap.newKeySet())  // Create if null
                          .onItem().call(set -> asyncMap.put(room, set).replace(set))  // Store the set
                          .onItem().call(set -> {
                              set.add(webSocket);  // Add the WebSocket to the room's set
                              broadcastToRoom(room, "User has joined the room: " + room, null);  // Notify others
                              return Uni.createFrom().voidItem();
                          })
                          .onItem().call(() -> {
                              // Set up handlers for the WebSocket
                              webSocket.handler(buffer -> {
                                  String message = buffer.toString();  // Incoming message
                                  broadcastToRoom(room, message, webSocket);  // Broadcast to room
                              });
      
                              webSocket.closeHandler(v -> {
                                  // Remove on close
                                  sharedData.getMutinyAsyncMap(SHARED_MAP_NAME)
                                      .onItem().transformToUni(map -> map.get(room))
                                      .onItem().call(set -> {
                                          if (set != null) {
                                              set.remove(webSocket);
                                              if (set.isEmpty()) {
                                                  map.remove(room);  // Clean up empty room
                                              }
                                              broadcastToRoom(room, "User has left the room: " + room, null);
                                          }
                                          return Uni.createFrom().voidItem();
                                      })
                                      .subscribe().with(ignored -> {}, err -> System.err.println("Error on close: " + err));
                              });
      
                              webSocket.exceptionHandler(err -> System.err.println("WebSocket error: " + err.getMessage()));
                              return Uni.createFrom().voidItem();
                          });
                  });
          }
      
          private void broadcastToRoom(String room, String message, ServerWebSocket exclude) {
              vertx.sharedData().getAsyncMap(SHARED_MAP_NAME)
                  .onSuccess(asyncMap -> asyncMap.get(room)
                      .onSuccess(set -> {
                          if (set != null) {
                              for (ServerWebSocket ws : set) {
                                  if (ws != exclude && ws.isOpen()) {  // Skip the sender and check if open
                                      ws.writeTextMessage(message);  // Send message
                                  }
                              }
                          }
                      })
                      .onFailure(err -> System.err.println("Broadcast error: " + err.getMessage())));
          }
      }
      
    2. Explanation of the Code:

      • Annotations:

        • @RouteBase(path = "/chat"): Defines the base path for all routes in this class.
        • @Route(path = "/:room", methods = "GET"): Handles GET requests to /chat/:room. It checks if the request is for a WebSocket upgrade.
      • WebSocket Handling:

        • ctx.request().toWebSocket(): Upgrades the connection to a WebSocket and returns a Uni (Mutiny's asynchronous result).
        • In setupWebSocket, we add the WebSocket to a shared map keyed by room. The shared map is a ConcurrentHashMap<String, Set<ServerWebSocket>>.
        • Event handlers:
          • handler(): Listens for incoming messages and broadcasts them.
          • closeHandler(): Removes the WebSocket from the room when the connection closes.
          • exceptionHandler(): Logs errors.
      • Room Management:

        • We use Vertx.sharedData().getAsyncMap() to access a shared map across the Vert.x event loop. This ensures that room data is accessible and thread-safe.
        • Each room is a set of ServerWebSocket instances.
      • Broadcasting:

        • The broadcastToRoom method sends messages to all WebSockets in the room, excluding the sender (if specified).
      • Reactive Elements:

        • Methods return Uni or use Mutiny chains to handle asynchronous operations without blocking.
    3. How Clients Connect and Interact:

      • The client-side code remains similar to what I provided earlier. For example:
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Chat App</title>
        </head>
        <body>
            <input type="text" id="messageInput" placeholder="Type a message">
            <button onclick="sendMessage()">Send</button>
            <div id="messages"></div>
        
            <script>
                const room = 'room1';  // Change to desired room
                const websocket = new WebSocket(`ws://localhost:8080/chat/${room}`);
        
                websocket.onopen = () => console.log('Connected to room:', room);
                websocket.onmessage = (event) => {
                    document.getElementById('messages').innerHTML += `<p>${event.data}</p>`;
                };
                websocket.onclose = () => console.log('Disconnected');
        
                function sendMessage() {
                    const message = document.getElementById('messageInput').value;
                    websocket.send(message);
                    document.getElementById('messageInput').value = '';
                }
            </script>
        </body>
        </html>
        
        • Connect to: ws://localhost:8080/chat/room1.
    4. Running and Testing:

      • Build and run the Quarkus app: mvn quarkus:dev.
      • Open multiple browser tabs with the HTML client, connecting to the same or different rooms (e.g., /chat/room1 vs. /chat/room2).
      • Verify that messages are only broadcasted within the same room.

    Advantages of This Approach

    • Reactivity: Uses Mutiny for non-blocking operations, making it more efficient for high-concurrency scenarios.
    • Scalability: Vert.x's shared data and event bus can be extended for distributed systems (e.g., using the event bus for cross-node broadcasting).
    • Integration: Easily integrates with other Quarkus reactive features, like databases or caching.

    Potential Improvements

    • Authentication: Add Quarkus Security to restrict access to rooms.
    • Error Handling: Enhance logging with a framework like SLF4J.
    • Persistence: Use a database or Redis to persist room data across restarts.
    • Testing: Write Quarkus tests for WebSocket routes using @QuarkusTest and Vert.x test utilities.

    If you encounter any issues or need further customizations (e.g., adding user nicknames or integrating with the event bus), let me know!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.