Search code examples
javaspringspring-websocketspring-messaging

Send STOMP ERROR from Spring Websocket program


I have a Spring Websocket Stomp application that accepts SUBSCRIBE requests.

In application I have a handler for SUBSCRIBE, that is,

 @Component
 public class SubscribeStompEventHandler implements ApplicationListener<SessionSubscribeEvent> {

    @Override
    public void onApplicationEvent(SessionSubscribeEvent event) {}
 }

that I use to validate subscription.

I would check something in the onApplicationEvent and send STOMP ERROR message back to client from this function.

I found this recipe How to send ERROR message to STOMP clients with Spring WebSocket? but I need to understand how to get outboundChannel.

I tried also the following code:

   public void sendStompError(SimpMessagingTemplate simpMessagingTemplate, String sessionId, String topic, String errorMessage) {

    StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
    headerAccessor.setMessage(errorMessage);
    headerAccessor.setSessionId(sessionId);
    headerAccessor.setLeaveMutable(true);
    simpMessagingTemplate.convertAndSendToUser(sessionId, topic, new byte[0], headerAccessor.getMessageHeaders());       
}

and I tried topic to be some subsciption topic and /queue/error topic. However I did not see messages propagating to client.

In Client, I use:

      stompClient.connect(headers
                , function (frame) {
                    console.log("Conn OK " + url);               
                }, function (error) {                       
                    console.log("Conn NOT OK " + url + ": " + JSON.stringify(error));
                });
        }

and my goal is to have function(error) called when I send STOMP ERROR.

Please advice me how exactly I can send proper STOMP ERROR, e.g. by getting Outboundchannel.


Solution

  • You can send ERROR Message like this:

    StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
    headerAccessor.setMessage(error.getMessage());
    headerAccessor.setSessionId(sessionId);
    this.clientOutboundChannel.send(MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders()));
    

    The following is just enough to inject that clientOutboundChannel:

     @Autowired
     @Qualifier("clientOutboundChannel")
     private MessageChannel clientOutboundChannel;
    

    Just because clientOutboundChannel bean is declared in the AbstractMessageBrokerConfiguration.

    UPDATE

    STOMP ERROR always closes connection? I am getting this effect. Code 1002.

    Yes, it is. See StompSubProtocolHandler.sendToClient():

           if (StompCommand.ERROR.equals(command)) {
                try {
                    session.close(CloseStatus.PROTOCOL_ERROR);
                }
                catch (IOException ex) {
                    // Ignore
                }
            }