Spring
Spring

Reputation: 11835

Spring websockets: message not published

I use Spring WebSockets with STOMP and SockJS for frontend. It works FINE but I have another difficulty.

This is backend code:

 @MessageMapping("/showAccountlist")
 @SendTo("/topic/accounts")
 public Account createPublishAccount(String name) throws Exception {

     return new Account(name);
 }

And this is front end code, which works FINE, all messages gets published to all clients.

 stompClient.send("/app/showAccountlist", {}, name);

BUT when I call my backend method from my java backend, with method name

createPublishAccount("Carlos");

Seems like messages does not get published. Any solution? Or this is not how it meant to work and it only works when it is triggered via SockJS?

This is my webconfig:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer  {

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

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

}

Upvotes: 5

Views: 3214

Answers (1)

Jakub Bibro
Jakub Bibro

Reputation: 1640

It seems like it's impossible to send message by calling @SendTo annotated method.

Spring recommanded way of sending messages is to use SimpMessagingTemplate. It is possible to have desination as an argument (in your case /topic/accounts) for example in convertAndSendToUser method (http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/messaging/simp/SimpMessagingTemplate.html).

Please see excerpt from Spring documentation (http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-handle-send):

What if you want to send messages to connected clients from any part of the application? Any application component can send messages to the "brokerChannel". The easiest way to do that is to have a SimpMessagingTemplate injected, and use it to send messages. Typically it should be easy to have it injected by type, for example:

@Controller
public class GreetingController {

    private SimpMessagingTemplate template;

    @Autowired
    public GreetingController(SimpMessagingTemplate template) {
        this.template = template;
    }

    @RequestMapping(path="/greetings", method=POST)
    public void greet(String greeting) {
        String text = "[" + getTimestamp() + "]:" + greeting;
        this.template.convertAndSend("/topic/greetings", text);
    }

}  

Upvotes: 6

Related Questions