Search code examples
springwebsocketstomp

Websocket Stomp - Broadcast(Topic,queue)


How do I broadcast to all subscribers(Topic) and the specified user(Channel).

this.messagingTemplate.convertAndSend(destination, message);
this.messagingTemplate.convertAndSendToUser(userId, destination, message);

Is that correct?

What is WebSocketConnectHandlerDecoratorFactory class for?

public final class WebSocketConnectHandlerDecoratorFactory implements WebSocketHandlerDecoratorFactory {

    private static final Log logger = LogFactory.getLog(WebSocketConnectHandlerDecoratorFactory.class);

    private final ApplicationEventPublisher eventPublisher;

    /**
     * Creates a new instance
     *
     * @param eventPublisher the {@link ApplicationEventPublisher} to use. Cannot be null.
     */
    public WebSocketConnectHandlerDecoratorFactory(ApplicationEventPublisher eventPublisher) {
        Assert.notNull(eventPublisher, "eventPublisher cannot be null");
        this.eventPublisher = eventPublisher;
    }

    @Override
    public WebSocketHandler decorate(WebSocketHandler handler) {
        return new SessionWebSocketHandler(handler);
    }

    private final class SessionWebSocketHandler extends WebSocketHandlerDecorator {

        public SessionWebSocketHandler(WebSocketHandler delegate) {
            super(delegate);
        }

        @Override
        public void afterConnectionEstablished(WebSocketSession wsSession)
                throws Exception {
            super.afterConnectionEstablished(wsSession);

            publishEvent(new SessionConnectEvent(this,wsSession));
        }

        private void publishEvent(ApplicationEvent event) {
            try {
                eventPublisher.publishEvent(event);
            }
            catch (Throwable ex) {
                logger.error("Error publishing " + event + ".", ex);
            }
        }
    }
}

Solution

    1. Correct.

    2. See its JavaDocs:

      /**
       * Ensures that a {@link SessionConnectEvent} is published in
       * {@link WebSocketHandler#afterConnectionEstablished(WebSocketSession)}. This
       * is necessary so that the {@link WebSocketSession} can be mapped to the
       * corresponding Spring {@link Session} to terminate any
       * {@link WebSocketSession} associated with a Spring {@link Session} that was
       * destroyed.
       *
       * @author Rob Winch
       * @since 1.0
       *
       * @see WebSocketRegistryListener
       */