Search code examples
javascriptspringwebsocketstompspring-websocket

Spring WebSockets Stomp.subscribe not working


I've been trying to implement a basic Spring WebSockets application following the official Spring guide. The files I have are the following:

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/chat");
        registry.setApplicationDestinationPrefixes("/message");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint("/ws-connect").setAllowedOrigins("*").withSockJS();
    }
}

MessageController.java

@Controller
public class MessageController {

    @MessageMapping(value = "/test")
    @SendTo("/private")
    public Message message(String messageText) {
        Message message = new Message();
        message.setMessage(messageText);r);
        message.setTimestamp(new Date());
        return message;
    }
}

sockets.js

var stompClient = null;

function connect() {
    var socket = new SockJS('http://localhost:8080/ws-connect');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {
        console.log('Connected: ' + frame);
        stompClient.subscribe('/chat/private', function(message) {
            console.log('Here');
            console.log('Message is: ' + message);
        });
        console.log('Here2');
    })
}

connect();

function sendMessage() {
    stompClient.send('/message/test', {}, "Hello self!");;
}

I have a button in my index.html that when clicked calls the sendMessage function and I get a console log that the message has been sent, however I never get the reply in the subscribe function. The client successfully connects to the WebSocket server and I get this outputted in the console. What am I doing wrong?


Solution

  • Change /private to /chat/private

    Change it like below :

    @Controller
    public class MessageController {
    
        @MessageMapping(value = "/test")
        @SendTo("/chat/private")
        public Message message(String messageText) {
            Message message = new Message();
            message.setMessage(messageText);
            message.setTimestamp(new Date());
            return message;
        }
    }