I am implementing a simple Spring Boot application which has a certain number of users connected via the WebSocket protocol. The application sends personal statistics to each user every 5 seconds.
I am using the @SendToUser
annotation to distinguish between users and personalize the statistics.
It seems to me that the method, annotated with @SendToUser
, can be only used as a message-handling method. This means that in order to receive the statistics the user should first send the message to the Spring Boot application, then the message-handling method will be called, and only then the statistics will be sent back.
As a result, the WebSocket protocol does now look very useful: the request is still initiated by a user (by the user's browser, to be precise). The only advantage is that you should not open new connection every time you want to retrieve the fresh statistics.
Is it possible to get rid of the messages sent from the users to the application at all? For example, to retrieve the list of the currently connected users every 5 seconds, then iterate over the list and send the message to every user one by one? Or a user still needs to initiate the statistics retrieval?
You can inject SimpMessagingTemplate
to any spring bean and send message to an user.
simpMessagingTemplate.convertAndSendToUser(username, "/destination", message);
You can retrieve list of the connected users by injecting SimpUserRegistry
bean.