Spring Websocket:如何从@MessageMapping回复中拦截返回类型

时间:2018-05-18 22:17:38

标签: spring spring-websocket

我有一个使用websocket的Spring应用程序

我可以进行连接并发送消息等。

@Controller是:

@MessageMapping("/ws/notification")
@SendTo("/topic/springframework.topic.websocket.reply")
public NotificationReply handleNotification(Notification notification) {
 ...
}

观察NotificationNotificationReply类型。

直到这里所有的工作如何预期

我有一个类ChannelInterceptorAdapter并使用以下方法:

  • public void postSend(Message<?> message, MessageChannel channel, boolean sent)

我能够以某种方式检索Notification类型。

更多细节:

但现在考虑 return 类型。

  • 我在哪里以及如何以NotificationReply类型的方式拦截?

1 个答案:

答案 0 :(得分:0)

在做了研究后,我意识到StompCommand枚举有以下内容:

public enum StompCommand {

    // client
    STOMP(SimpMessageType.CONNECT),
    CONNECT(SimpMessageType.CONNECT),
    DISCONNECT(SimpMessageType.DISCONNECT),
    SUBSCRIBE(SimpMessageType.SUBSCRIBE, true, true, false),
    UNSUBSCRIBE(SimpMessageType.UNSUBSCRIBE, false, true, false),
    SEND(SimpMessageType.MESSAGE, true, false, true),
    ACK(SimpMessageType.OTHER),
    NACK(SimpMessageType.OTHER),
    BEGIN(SimpMessageType.OTHER),
    COMMIT(SimpMessageType.OTHER),
    ABORT(SimpMessageType.OTHER),

    // server
    CONNECTED(SimpMessageType.OTHER),
    RECEIPT(SimpMessageType.OTHER),
    MESSAGE(SimpMessageType.MESSAGE, true, true, true),
    ERROR(SimpMessageType.OTHER, false, false, true);

    ...

因此观察MESSAGE在'服务器'下。因此,解决方案是为case添加MESSAGE,如下所示:

    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {

        StompHeaderAccessor stompHeaderAccessor = StompHeaderAccessor.wrap(message);

           ....

        switch(stompHeaderAccessor.getCommand()) {
            case CONNECT:
                logger.info("postSend ...");
                logger.info("STOMP Connect");
                break;
            ...
            case MESSAGE:
                logger.info("postSend ...");
                logger.info("STOMP MESSAGE");
                .... do more
                break;
            ...
            case SEND:
                logger.info("postSend ...");
                logger.info("STOMP Send");
                printDetails(message, stompHeaderAccessor);
                break;

        ...
    } 

如果您想查看payload的{​​{1}},可以执行以下操作: