Recently, I've been working on setting up a basic Spring WebSockets application by following the official Spring guide. The main files that I have created for this project are:
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!");;
}
In my index.html file, there is a button that triggers the sendMessage function when clicked. Although the console confirms that the message has been sent, I am not receiving any replies in the subscribe function. Despite successfully connecting to the WebSocket server and logging the expected output, I'm puzzled as to what mistake I might have made. Can anyone pinpoint where I may have gone wrong?