| | |
| | | package com.ard.sample.component.websocket.config; |
| | | |
| | | import org.springframework.context.annotation.Bean; |
| | | import com.ard.sample.component.websocket.handler.*; |
| | | import com.ard.sample.component.websocket.interceptor.DockHandshakeInterceptor; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.web.socket.server.standard.ServerEndpointExporter; |
| | | import org.springframework.web.socket.config.annotation.EnableWebSocket; |
| | | import org.springframework.web.socket.config.annotation.WebSocketConfigurer; |
| | | import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; |
| | | |
| | | /** |
| | | * 启用WebSocket支持,注册端点处理器 |
| | | */ |
| | | @Configuration |
| | | public class WebSocketDockConfig { |
| | | @EnableWebSocket // 启用原生WebSocket支持 |
| | | public class WebSocketDockConfig implements WebSocketConfigurer { |
| | | |
| | | // 自动注册@ServerEndpoint注解的类 |
| | | @Bean |
| | | public ServerEndpointExporter serverEndpointExporter() { |
| | | return new ServerEndpointExporter(); |
| | | @Autowired |
| | | private DockWebSocketHandler dockWebSocketHandler; |
| | | |
| | | // 注册WebSocket处理器和路径 |
| | | @Override |
| | | public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { |
| | | // 1. 注册处理器:路径 "/ws/dock/**" 由 DockWebSocketHandler 处理 |
| | | // 2. 添加握手拦截器:验证用户身份DockHandshakeInterceptor |
| | | // 3. 配置跨域:允许所有域名(生产环境需限制) |
| | | registry.addHandler(dockWebSocketHandler, "/ws/dock/**") |
| | | .addInterceptors(new DockHandshakeInterceptor()) |
| | | .setAllowedOrigins("*"); |
| | | |
| | | } |
| | | } |