Search code examples
springspring-bootwebsocketspring-websocketspring-messaging

Spring Boot WebSockets notifications


In my Spring Boot application I'm trying to implement a notifications functionality based on WebSockets.

I have provided a following configuration:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/notifications").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic", "/queue");
    }

}

and trying to use SimpMessagingTemplate in order to send a message from server side to a specific client(user).

@Autowired
private SimpMessagingTemplate simpMessagingTemplate;

public void sendMessages() {
    simpMessagingTemplate.convertAndSendToUser(%user%, "/horray", "Hello, World!");
}

Right now I don't understand a few things:

  1. What value should be used for %user% parameter of simpMessagingTemplate.convertAndSendToUser method ?

  2. What is the correlation between my /notifications endpoint registered in WebSocketConfig.registerStompEndpoints method and destination parameter of simpMessagingTemplate.convertAndSendToUser method and how to properly use it?

  3. How to protect the users from reading other people's messages on the client ?


Solution

  • The user parameter is the name that the client use when he subscribes the destination, see Spring Reference Chapter 26.4.11 User Destinations

    Destination vs Endpoint:

    • Endpoint is the url where the websocket/message brocker is listening
    • Destination is the topic or subject within the message brocker