1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.ard.sample.component.websocket.config;
 
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.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
 
@Configuration
@EnableWebSocket // 启用原生WebSocket支持
public class WebSocketDockConfig implements WebSocketConfigurer {
 
    @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("*");
 
    }
}