【问题标题】:Broadcast messages with websockets and SpringBoot使用 websockets 和 SpringBoot 广播消息
【发布时间】:2018-04-02 16:47:28
【问题描述】:

我正在尝试了解如何使用带有 Spring Boot 的 websocket 将消息发布/广播到 Javascript 应用程序。我能找到的所有示例都使用了StompJs 客户端 - 但是我无法在我的客户端代码中使用StompJs,而且我不确定我的后端是否正确,这无济于事。

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/subscribe")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");
    }

}

只需使用简单的@Scheduled 生成每 5 秒一次的时间,并将其发送到 time 主题(嗯,我相信这就是它正在做的......)

@Component
@Slf4j
public class TimeSender {
    private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss");

    private SimpMessagingTemplate broker;

    @Autowired
    public TimeSender(final SimpMessagingTemplate broker) {
        this.broker = broker;
    }

    @Scheduled(fixedRate = 5000)
    public void run() {
        String time = LocalTime.now().format(TIME_FORMAT);

        log.info("Time broadcast: {}", time);

        broker.convertAndSend("/topic/time", "Current time is " + time);
    }
}

在尝试对此进行测试时,我有些困惑。使用 Chrome 的 Simple websocket client 插件,我必须在我的请求末尾添加 websocket 才能连接。一个连接想ws://localhost:8080/subscribe/websocket 没有websocket 我无法连接,但我在任何示例或 Spring 文档中都找不到这个?

第二个问题是如何订阅时间主题?所有StompJs 客户都调用client.subscribe("time") 之类的东西。

我试过ws://localhost:8080/subscribe/topic/time/websocket,但没有收到任何时间戳。

我不确定我的后端代码是否有误,我的网址是否有误,或者我只是缺少其他内容。

注意:上面缺少我的@Controller,因为我现在只专注于将消息从 Spring 推送到客户端,而不是接收消息,而且我的理解是控制器只是处理传入的?

【问题讨论】:

  • 您是否解决了这个问题?我遇到了类似的问题。

标签: java spring-boot websocket


【解决方案1】:

好吧,我想如果一个人足够痴迷地搜索,答案最终会出现。几乎在找到您的帖子后,我立即在http://www.marcelustrojahn.com/2016/08/spring-boot-websocket-example/ 找到了我需要的答案。有一个非常好的示例,基本上可以满足您的描述。不同之处在于他们使用 Spring SimpMessagingTemplate 将消息发送到队列。一旦我遵循他的模式,这一切就像一个魅力。下面是相关代码sn-p:

@Autowired
SimpMessagingTemplate template

@Scheduled(fixedDelay = 20000L)
@SendTo("/topic/pingpong")
public void sendPong() {
   template.convertAndSend("/topic/pingpong", "pong (periodic)")
}

方法是void,所以convertAndSend() 方法处理主题的发布,而不是我在网上看到的几乎所有其他教程所表明的返回语句。这有助于解决我的问题。

【讨论】:

    猜你喜欢
    • 2014-08-25
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多