Can you use io.quarkus.websockets.next and java to create a chat. And this chat should…
- 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
- Assistant
To create a chat application using Quarkus with WebSocket support and room-based messaging, we can leverage the
io.quarkus.websockets.nextextension (which is built on top of the Jakarta WebSocket API). This allows us to handle multiple rooms where only users in the same room receive messages.
✅ Key Concepts
- WebSocket Endpoint: A single WebSocket endpoint (
/chat) will handle all connections. - Rooms: A
Map<String, Set<Session>>keeps track of all users in each room. - Session Tracking: A
Map<Session, String>tracks which room each user is in. - Message Handling:
- Users must join a room by sending a JSON message like
{"action": "join", "room": "general"}. - Messages are broadcast only to users in the same room.
- Users must join a room by sending a JSON message like
🧱 Step-by-Step Implementation
1. Add Dependency (if not already included)
Add the WebSocket extension to your
pom.xml:<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-websocket</artifactId> </dependency>
2. WebSocket Endpoint Class
Create a class that handles WebSocket connections, joins, and messages.
package com.example.chat; import jakarta.websocket.*; import jakarta.websocket.server.ServerEndpoint; import jakarta.json.Json; import jakarta.json.JsonObject; import java.io.IOException; import java.io.StringReader; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; @ServerEndpoint("/chat") public class ChatWebSocket { private static final Map<String, Set<Session>> rooms = new ConcurrentHashMap<>(); private static final Map<Session, String> sessionRoom = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session) { System.out.println("User connected: " + session.getId()); } @OnMessage public void onMessage(String message, Session session) { try { JsonObject json = Json.createReader(new StringReader(message)).readObject(); String action = json.getString("action"); if ("join".equals(action)) { String room = json.getString("room"); rooms.computeIfAbsent(room, k -> new CopyOnWriteArraySet<>()).add(session); sessionRoom.put(session, room); System.out.println("User " + session.getId() + " joined room: " + room); } else { String room = sessionRoom.get(session); if (room != null) { Set<Session> usersInRoom = rooms.get(room); for (Session user : usersInRoom) { if (!user.equals(session)) { try { user.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } } } } } } catch (Exception e) { e.printStackTrace(); } } @OnClose public void onClose(Session session) { String room = sessionRoom.remove(session); if (room != null) { rooms.get(room).remove(session); System.out.println("User " + session.getId() + " left room: " + room); } } @OnError public void onError(Throwable error, Session session) { System.err.println("Error for user " + session.getId() + ": " + error.getMessage()); error.printStackTrace(); } }
🧪 Client Example (JavaScript)
You can test this with a simple JavaScript client:
<!DOCTYPE html> <html> <body> <script> const ws = new WebSocket('ws://localhost:8080/chat'); ws.onopen = () => { console.log('Connected to WebSocket'); ws.send(JSON.stringify({ action: 'join', room: 'general' })); }; ws.onmessage = (event) => { console.log('Received: ', event.data); }; </script> </body> </html>
📌 Notes
- Thread Safety: We use
ConcurrentHashMapandCopyOnWriteArraySetto ensure thread-safe access. - Security: In a real-world app, you'd validate room names and handle authentication.
- Scalability: For production, consider using a message broker like RabbitMQ or Kafka for distributed rooms.
🧠 Summary
This implementation provides a scalable, room-based chat system using Quarkus and Jakarta WebSockets. Each user joins a room, and messages are only sent to others in the same room. You can extend this by adding features like user authentication, room creation, or persistent message storage.
- WebSocket Endpoint: A single WebSocket endpoint (
- User
switch to use io.quarkus.vertx.web
- Assistant
To switch from using
io.quarkus.websockets.next(based on Jakarta WebSocket) to usingio.quarkus.vertx.web(based on Vert.x Web), we need to restructure the chat application to use Vert.x's WebSocket API instead of the standard WebSocket annotations.
✅ Key Concepts
- Vert.x Web: A lightweight, non-blocking, event-driven web framework built on top of Vert.x.
- WebSocketHandler: A handler used to manage WebSocket connections.
- WebSocket: The actual connection object that allows sending and receiving messages.
- Rooms: A
Map<String, Set<WebSocket>>to track which users are in which rooms. - Session Management: A
Map<WebSocket, String>to track the room a user is in.
🧱 Step-by-Step Implementation
1. Add Dependency (if not already included)
Ensure the
quarkus-vertx-webextension is added to yourpom.xml:<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-vertx-web</artifactId> </dependency>
2. Create the WebSocket Endpoint
Define a class that sets up the WebSocket endpoint using Vert.x Web.
package com.example.chat; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.WebSocketHandler; import jakarta.json.Json; import jakarta.json.JsonObject; import java.io.StringReader; import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; public class ChatWebSocket { private static final Map<String, Set<WebSocket>> rooms = new ConcurrentHashMap<>(); private static final Map<WebSocket, String> sessionRoom = new ConcurrentHashMap<>(); public static void setupWebSocket(Vertx vertx) { Router router = Router.router(vertx); router.websocket("/chat", ws -> { // Handle WebSocket text messages ws.textHandler(message -> { try { JsonObject json = Json.createReader(new StringReader(message)).readObject(); String action = json.getString("action"); if ("join".equals(action)) { String room = json.getString("room"); rooms.computeIfAbsent(room, k -> new CopyOnWriteArraySet<>()).add(ws); sessionRoom.put(ws, room); System.out.println("User joined room: " + room); } else { String room = sessionRoom.get(ws); if (room != null) { Set<WebSocket> usersInRoom = rooms.get(room); for (WebSocket user : usersInRoom) { if (!user.equals(ws)) { user.writeTextMessage(message); } } } } } catch (Exception e) { e.printStackTrace(); } }); // Handle WebSocket close ws.closeHandler(v -> { String room = sessionRoom.remove(ws); if (room != null) { rooms.get(room).remove(ws); System.out.println("User left room: " + room); } }); }); // Start HTTP server with the router HttpServer server = vertx.createHttpServer(); server.requestHandler(router).listen(8080, result -> { if (result.succeeded()) { System.out.println("Chat server started on port 8080"); } else { System.err.println("Failed to start chat server: " + result.cause()); } }); } }
3. Initialize the WebSocket in Quarkus
In a Quarkus application, you can initialize the WebSocket endpoint using a
@Startupbean or a@PostConstructmethod. Here's an example using@PostConstruct:package com.example.chat; import io.quarkus.vertx.VertxContext; import io.vertx.core.Vertx; import jakarta.annotation.PostConstruct; import jakarta.inject.Inject; import jakarta.enterprise.context.ApplicationScoped; @ApplicationScoped public class WebSocketInitializer { @Inject Vertx vertx; @PostConstruct void init() { ChatWebSocket.setupWebSocket(vertx); } }
4. Client Example (JavaScript)
You can test the chat with the following HTML/JavaScript:
<!DOCTYPE html> <html> <body> <script> const ws = new WebSocket('ws://localhost:8080/chat'); ws.onopen = () => { console.log('Connected to WebSocket'); ws.send(JSON.stringify({ action: 'join', room: 'general' })); }; ws.onmessage = (event) => { console.log('Received: ', event.data); }; </script> </body> </html>
📌 Notes
- Thread Safety: We use
ConcurrentHashMapandCopyOnWriteArraySetto ensure safe concurrent access. - Scalability: This implementation is suitable for small-scale applications. For production, consider using a message broker like RabbitMQ or Kafka for distributed messaging.
- Quarkus Integration: The
Vertxinstance is injected via CDI, and the WebSocket is set up in a@PostConstructmethod, which is the standard way to initialize components in Quarkus.
🧠 Summary
By using
io.quarkus.vertx.web, you can build a non-blocking, event-driven chat server that supports room-based messaging. This approach leverages the power of Vert.x and is well-suited for high-performance applications. The code is structured to be clean, modular, and easy to extend with additional features like user authentication or persistent message storage.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.