【发布时间】: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