I have read these documentations -> websockets-next and reference guide websockets-next.
I understand how a chat message could be implemented, because the client reacts to the endpoints but I have no idea how the server could send messages to the clients if updates occure on the server.
Secondly, how can I send not only text messages but whole DTOs?
I have never worked with sockets so I only know REST-Endpoints.
My example code:
DTO for the clients:
@Data
public class InformationForClientDTO {
private List<FinancialCalculationsDTO> list;
private int version;
}
Code on the server:
@ApplicationScoped
public class ServerCode {
public void someCalculation(){
//Server has reached some point which is important for clients. Send listForClients to all connected clients:
Arraylist<InformationForClientDTO> listForClients;
//How to send this list to the clients? How can I call the websocket with all clients and send them the DTOs?
}
}
Code-example From the quarkus wiki:
@WebSocket(path = "/chat/{username}")
public class ChatWebSocket {
// Declare the type of messages that can be sent and received
public enum MessageType {USER_JOINED, USER_LEFT, CHAT_MESSAGE}
public record ChatMessage(MessageType type, String from, String message) {
}
@Inject
WebSocketConnection connection;
@OnOpen(broadcast = true)
public ChatMessage onOpen() {
return new ChatMessage(MessageType.USER_JOINED, connection.pathParam("username"), null);
}
@OnClose
public void onClose() {
ChatMessage departure = new ChatMessage(MessageType.USER_LEFT, connection.pathParam("username"), null);
connection.broadcast().sendTextAndAwait(departure);
}
@OnTextMessage(broadcast = true)
public ChatMessage onMessage(ChatMessage message) {
return message;
}
}