更改 websocket 范围从应用程序到会话/视图

问题描述

我用教程创建了一个基本的网络套接字。

这是一个配置:

@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("/chat");
         registry.addEndpoint("/chat").withSockJS();
    }
}

这里是消息处理控制器:

@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
    return new OutputMessage("Hello World!");
}

一切正常,但根据我的调查,认情况下 WebSockets 似乎有一个应用程序范围(通过连接到通道,我可以看到来自所有用户的所有调用)。

我想要做的是只能看到来自当前用户会话或当前视图的调用。 关于如何应用这些配置的任何想法?

解决方法

我能够解决这个难题,所以我将与您分享我的发现。

首先,我发现一个简单的内存消息代理无法处理这个信息:

    /*
     * This enables a simple (in-memory) message broker for our application.
     * The `/topic` designates that any destination prefixed with `/topic`
     * will be routed back to the client.
     * It's important to keep in mind,this will not work with more than one
     * application instance,and it does not support all of the features a
     * full message broker like RabbitMQ,ActiveMQ,etc... provide.
     */

但这是一种误导,因为它可以通过 @SendToUser 注释轻松实现。 此外,重要的是,现在在客户端,您需要在订阅频道时添加额外的前缀 /user/,因此解决方案是:

  1. 在服务器端:将 @SendTo("/topic/messages") 更改为 @SendToUser("/topic/messages")
  2. 在客户端:/topic/messages 进入 /user/topic/messages

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...