springboot实现websocket通信握手失败报错的解决方法

一开始是按照这份代码写的https://www.cnblogs.com/best/p/5695570.html,但一直报错200,后发现是因为:
如果使用独立的servlet容器,那这份代码没问题;
但如果是使用springboot的内置容器,则需要多几个步骤:
1、引入依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2、创建websocket配置类:

@Configuration
public class WebSocketConfig {
    
    
    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
    
    
        return new ServerEndpointExporter();
    }
}

就可连接成功,原因是:ServerEndpointExporter 会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。如果使用独立的servlet容器,就不需要注入ServerEndpointExporter,因为它将由容器自己提供和管理。如果是使用springboot的内置容器则需要手动注入

猜你喜欢

转载自blog.csdn.net/Xyouzi/article/details/113914558