Send STOMP ERROR from Spring Websocket program

五迷三道 提交于 2019-12-21 21:37:29

问题


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.


回答1:


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
            }
        }


来源:https://stackoverflow.com/questions/39641477/send-stomp-error-from-spring-websocket-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!