1. 程式人生 > >spring boot下使用WebSocket javax時報錯:Error during WebSocket handshake: Unexpected response code: 404

spring boot下使用WebSocket javax時報錯:Error during WebSocket handshake: Unexpected response code: 404

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包

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

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-