Java实战:Spring Boot实现WebSocket实时通信
warning:
这篇文章距离上次修改已过209天,其中的内容可能已经有所变动。
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
这段代码定义了一个配置类WebSocketConfig
,该类实现了WebSocketMessageBrokerConfigurer
接口,用于配置Spring Boot中的WebSocket支持。在这个配置中,我们定义了一个WebSocket端点/ws
,并且启用了SockJS,这样就可以支持不支持WebSocket的浏览器。我们还定义了一个简单的消息代理,将前缀为/topic
的消息路由到代理服务器,并将前缀为/app
的消息视为应用程序特定的消息。这样,客户端就可以通过/topic/someTopic
订阅主题,通过/app/someDestination
发送消息。
评论已关闭