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;
}
}
//EDIT For anyone looking for more information about websockets-next, I found this: Discussion about websockets next
but I have no idea how the server could send messages to the clients if updates occure on the server.
You can inject io.quarkus.websockets.next.OpenConnections
which provides a convenient access to all open connections. Note that this feature is not documented yet but there's an open issue.
Secondly, how can I send not only text messages but whole DTOs?
In your case, you don't send a plain text message but a Java record that is converted to JSON by default. WS next attempt to encode/decode any POJO with Jackson. So if your DTO fulfills the requirements the requirements of Jackson it's converted automatically. You can also provide a custom codec - see https://quarkus.io/guides/websockets-next-reference#serialization-and-deserialization.