【问题标题】:Change websocket scope (from application to session/view)更改 websocket 范围(从应用程序到会话/视图)
【发布时间】:2021-04-14 07:01:16
【问题描述】:

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

这是一个配置:

@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 似乎具有应用程序范围(通过连接到通道,我可以看到来自所有用户的所有调用)。

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

【问题讨论】:

    标签: java spring-boot websocket spring-websocket spring-messaging


    【解决方案1】:

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

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

        /*
         * 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

    【讨论】:

      猜你喜欢
      • 2013-05-16
      • 1970-01-01
      • 2017-05-09
      • 2011-07-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2019-03-02
      相关资源
      最近更新 更多