从Spring Websocket程序发送STOMP错误

4
我是一名有用的助手,可以为您翻译文本。
我有一个Spring Websocket Stomp应用程序,可以接受SUBSCRIBE请求。
在应用程序中,我有一个处理器用于SUBSCRIBE。
 @Component
 public class SubscribeStompEventHandler implements ApplicationListener<SessionSubscribeEvent> {

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

我使用它来验证订阅。

我会在onApplicationEvent中检查某些内容,并从该函数向客户端发送STOMP ERROR消息。

我发现这个配方 如何使用Spring WebSocket向STOMP客户端发送错误消息?,但我需要了解如何获取outboundChannel。

我也尝试了以下代码:

   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());       
}

我尝试订阅主题和/queue/error主题,但是我没有看到消息传播到客户端。

在客户端中,我使用:

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

我的目标是在发送STOMP ERROR时调用函数(error)。请指导我如何准确地发送STOMP ERROR,例如通过获取Outboundchannel。
1个回答

15

您可以像这样发送ERROR消息:

StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
headerAccessor.setMessage(error.getMessage());
headerAccessor.setSessionId(sessionId);
this.clientOutboundChannel.send(MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders()));
以下内容足以注入 clientOutboundChannel:
 @Autowired
 @Qualifier("clientOutboundChannel")
 private MessageChannel clientOutboundChannel;

仅仅因为clientOutboundChannel bean是在AbstractMessageBrokerConfiguration中声明的。

更新

STOMP错误总是关闭连接?我正在遇到这个现象。错误码1002。

是的,确实如此。请参见StompSubProtocolHandler.sendToClient()

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

Artem,请问您能否澄清一下:STOMP ERROR是否总是会关闭连接?我遇到了这个问题。错误代码为1002。 - onkami
请在我的回答中查看并更新。 - Artem Bilan
StompClient 如何接收错误消息?需要进行特殊配置吗? - hurelhuyag
@ArtemBilan,你知道在使用SpringBoot时有没有其他的替代方法可以正确地发送ERROR帧并等待一段时间让客户端处理它们吗? - Fernando Miguélez
如何获取会话以关闭连接? - python
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接