Search code examples
javaspringspring-websocketspring-messaging

How to detect Spring websocket stomp subscription messages (frames)?


I'm using Spring 5: how do I detect SUBSCRIBE messages from a Stomp client?

Per my understanding, @SubscribeMapping should make my controller method be called whenever a client subscribes to a topic, but that's not happening.

Here's my server controller:

@Controller
public class MessageController {

    // ...

    @MessageMapping("/chat/{mId}")
    @SendTo("/topic/messages")
    public OutputMessage send(Message message, @DestinationVariable("mId") String mid, MessageHeaders headers, MessageHeaderAccessor accessor) throws Exception {
        // ...
    }

    @SuppressWarnings("unused")
    @SubscribeMapping({ "/", "/chat", "/topic/messages", "/messages", "/*" })
    public void listen(Message message, MessageHeaders headers, MessageHeaderAccessor accessor) throws Exception {
        int i = 0;
        System.out.println("subscribed");
    }

}

Server configuration:

@Configuration
@ComponentScan(basePackages= { "websockets" })
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

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

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
        WebSocketMessageBrokerConfigurer.super.configureWebSocketTransport(registry);
    }
}

And the javascript client:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Chat WebSocket</title>
        <script src="sockjs.js"></script>
        <script src="stomp.js"></script>

        <script type="text/javascript">

            // ...

            function connect() {
                var sock = new SockJS('/<webapp-context>/chat');

                stompClient = Stomp.over(sock);  
                stompClient.connect({}, function(frame) {
                    setConnected(true);
                    console.log('Connected: ' + frame);
                    stompClient.subscribe('/topic/messages', function(messageOutput) {
                        showMessageOutput(JSON.parse(messageOutput.body));
                    });
                    stompClient.subscribe('/topic/messages/13', function(messageOutput) {
                        showMessageOutput(JSON.parse(messageOutput.body));
                    });
                });
            }

            // ...

        </script>
    </head>
    <body onload="/*disconnect()*/">

        <!-- ... -->

    </body>
</html>

The code has been adapted from Intro to WebSockets with Spring.

As indicated in this answer and in the docs, I can just use an interceptor, but how does @SubscribeMapping work then?


Solution

  • You need to register "topic" also as application destination topic config.setApplicationDestinationPrefixes({"/app", "/topic"});.

    Otherwise Spring won't forward the subscribe message to the application and just forward it to the message broker channel.