I have a spring boot server and a client which are connected via Websockets using STOMP.
My use case is that I want to send data to the client, every time a http request to a specific endpoint is made. All the tutorials I found, only show the case, that the client sends some data to "/hello" and the server reacts by sending data to "topic/greetings":
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
What I need is a controller method that sends data without the need of the message mapping. It should just send data to the client every time someone performs a get request to the endpoint. I tried the following, but it didn't work:
@Autowired
private SimpMessagingTemplate msgTemplate;
@SendTo("topic/data-received")
@RequestMapping(value = "/send-data", method = RequestMethod.POST)
public String sendData(@RequestHeader(value = "id") String id,
@RequestHeader(value = "data") String data) {
User user = new User();
user.id = UUID.fromString(id);
user.stringData = data;
database.saveStringData(user);
msgTemplate.convertAndSend("topic/data-received", "data sent!!");
return "successful";
}
Here is my client code:
function connect() {
var socket = new SockJS('/clipboard-websocket');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('topic/data-received/', function (message) {
alert("Data received!!");
});
}
And that's my WebSocket config:
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/clipboard-websocket").withSockJS();
}
Trailing slash is missing in the destination
msgTemplate.convertAndSend("/topic/data-received", "data sent!!");