spring boot下使用WebSocket javax时报错:Error during WebSocket handshake: Unexpected response code: 404...

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

spring boot下使用WebSocket javax时报错:

WebSocket connection to 'ws://localhost:8888/websocket' failed: Error during WebSocket handshake: Unexpected response code: 404

代码如下:

前端

//获得WebSocket对象
var websocket = new WebSocket("ws://localhost:8888/websocket");  

后端

@ServerEndpoint(value = "/websocket")
@Service
public class MsgWebSocket {
    /**
     * 收到消息
     *
     * @param message 客户端发送过来的消息
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        ...
    }
}   

解决方案:

step1. pom中引入jar包


    org.springframework.boot
    spring-boot-starter-websocket


step2. 添加Bean ServerEndpointExporter

@Component
public class WebSocketConfig {

    /**
     * 使用spring boot时,使用的是spring-boot的内置容器,
     * 如果要使用WebSocket,需要注入ServerEndpointExporter
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

完整代码:

[email protected]:valsong/blog-demo.git
中的websocket-javax项目

转载于:https://my.oschina.net/valsong/blog/3044096

你可能感兴趣的:(spring boot下使用WebSocket javax时报错:Error during WebSocket handshake: Unexpected response code: 404...)