Java WebSocket握手期间出错:意外响应代码:400 Spring boot WebSocket

Java WebSocket握手期间出错:意外响应代码:400 Spring boot WebSocket,java,spring,spring-boot,websocket,Java,Spring,Spring Boot,Websocket,我正在尝试实现WebSocket。我的代码: 在spring security中,我允许路径w/e authentication @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf() .disable() .authorizeRequests() .antMatchers

我正在尝试实现WebSocket。我的代码:

在spring security中,我允许路径w/e authentication

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/register","/login","/testAuth","/web","/ws").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
和ws的配置

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new WsMessageHandler(), "/ws")
                .addInterceptors(new CustomInterceptor())
                .setAllowedOrigins("*")
                .setHandshakeHandler(new DefaultHandshakeHandler())
                .withSockJS();
    }
}
`

然而,我收到了一个错误:

到“ws://localhost:8080/ws”的WebSocket连接失败:过程中出错 WebSocket握手:意外响应代码:400


这是什么原因造成的?一切都应该是正确的。感谢您的回答

我发现您的代码有一些错误:

  • 如果使用WebSocket()作为客户端,则应在WebSocketConfig中使用SocktJS()进行注释。你喜欢吗
  • @配置
    @启用WebSocket
    公共类WebSocketConfig2实现WebSocketConfigurer{
    @凌驾
    公共无效注册表WebSockEthandlers(WebSocketHandlerRegistry注册表){
    registry.addHandler(新的WsMessageHandler(),“/ws”)
    .addInterceptors(新的CustomInterceptor())
    .setAllowedOrigins(“*”)
    .setHandshakeHandler(新的DefaultHandshakeHandler())
    //.withSockJS()
    ;
    }
    }
    
  • 你的客户端js代码是错误的。没有ws。您应该使用exampleSocket发送。如下
  • var exampleSocket=newwebsocket(“ws://localhost:8081/ws”,“protocolOne”);
    exampleSocket.onopen=函数(ws){
    console.log('--------------',ws);
    //已连接Web套接字,请使用send()发送数据
    示例socket.send(“要发送的消息”);
    警报(“消息已发送…”);
    };
    
  • 当在客户端发送websocket时,您指向一个名为“protocolOne”的协议,您应该将其返回到CustomInterceptor中。你可以做如下的事情
  • 公共类CustomInterceptor实现握手接口{
    @凌驾
    公共布尔值beforeHandshake(ServerHttpRequest ServerHttpRequest,ServerHttpResponse ServerHttpResponse,WebSocketHandler WebSocketHandler,映射)引发异常{
    返回true;
    }
    @凌驾
    握手后公共无效(ServerHttpRequest ServerHttpRequest,ServerHttpResponse ServerHttpResponse,WebSocketHandler WebSocketHandler,@Nullable异常e){
    if(serverHttpRequest.getHeaders()==null)
    返回;
    if(serverHttpRequest.getHeaders().get(“Sec WebSocket协议”)==null)
    返回;
    字符串协议=(字符串)serverHttpRequest.getHeaders().get(“Sec WebSocket协议”).get(0);
    if(协议==null)
    返回;
    serverHttpResponse.getHeaders().add(“Sec WebSocket协议”,协议);
    }
    }
    
      public class CustomInterceptor implements HandshakeInterceptor {
            @Override
            public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
                return true;
            }
        
            @Override
            public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, @Nullable Exception e) {
        
            }
        }
    
    var exampleSocket = new WebSocket("ws://localhost:8080/ws", "protocolOne");
               exampleSocket.onopen = function() {
                  
                  // Web Socket is connected, send data using send()
                  ws.send("Message to send");
                  alert("Message is sent...");
               };