1. 程式人生 > >springboot+websocket的簡單實現,解決websocket failed: Error during WebSocket handshake: Unexpected response

springboot+websocket的簡單實現,解決websocket failed: Error during WebSocket handshake: Unexpected response

編輯器:idea。tomcat是springboot內建的tomcat,一開始出現

websocket failed: Error during WebSocket handshake: Unexpected response

這個問題的原因是,我一開始在專案中沒有在注入ServerEndpointExporter ,後來注入後就能完整的運行了。

下面開始簡單的實現過程:

我的專案結構:(該實現是客戶端的實現,沒有設定服務端的實現)

一、首先,建立springboot專案,在pox.xml中加入(下面是我的pom.xml的dependencies裡的全部依賴,因為,這個是最簡單的入門例子,所以只有主要的websocket和web依賴)

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--websocket連線需要使用到的包-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

二、建立一個頁面index.html,前端跳轉後端的一些必要程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Java後端WebSocket的Tomcat實現</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">傳送訊息</button>
<hr/>
<button onclick="closeWebSocket()">關閉WebSocket連線</button>
<hr/>
<div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判斷當前瀏覽器是否支援WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket('ws://localhost:8080/websocket');
    }
    else {
        alert('當前瀏覽器 Not support websocket')
    }

    //連線發生錯誤的回撥方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket連線發生錯誤");
    };

    //連線成功建立的回撥方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket連線成功");
    }

    //接收到訊息的回撥方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //連線關閉的回撥方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket連線關閉");
    }

    //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //將訊息顯示在網頁上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //關閉WebSocket連線
    function closeWebSocket() {
        websocket.close();
    }

    //傳送訊息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

三、後端的socket處理

WebSockTest.java
/**
 * @ServerEndPoint 註解是一個類層次的註解,它的功能主要是將目前的類定義成一個websocket伺服器端,
 * 註解的值將被用於監聽使用者連線的終端訪問URL地址,客戶端可以通過這個URL連線到websocket伺服器端
 */
@ServerEndpoint("/websocket")
@Component
public class WebSockTest {
    private static int onlineCount=0;
    private static CopyOnWriteArrayList<WebSockTest> webSocketSet=new CopyOnWriteArrayList<WebSockTest>();
    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);//加入set中
        addOnlineCount();
        System.out.println("有新連線加入!當前線上人數為"+getOnlineCount());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有一連線關閉!當前線上人數為" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("來自客戶端的訊息:"+message);
//        群發訊息
        for (WebSockTest item:webSocketSet){
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        System.out.println("發生錯誤!");
        throwable.printStackTrace();
    }
//   下面是自定義的一些方法
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    
    public static synchronized int getOnlineCount(){
        return onlineCount;
    }
    public static synchronized void addOnlineCount(){
        WebSockTest.onlineCount++;
    }
    public static synchronized void subOnlineCount(){
        WebSockTest.onlineCount--;
    }
}

四、springboot要注入ServerEndpointExporter 

注入ServerEndpointExporter,這個bean會自動註冊使用了@ServerEndpoint註解宣告的Websocket endpoint。 要注意,如果使用獨立的servlet容器,而不是直接使用springboot的內建容器,就不要注入ServerEndpointExporter, 因為它將由容器自己提供和管理。

WebSocketConfig.java

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

使用springboot的唯一區別是要@Component宣告下,而使用獨立容器是由容器自己管理websocket的,但在springboot中連容器都是spring管理的。 雖然@Component預設是單例模式的,但springboot還是會為每個websocket連線初始化一個bean,所以可以用一個靜態set儲存起來。

全部的程式碼就是這樣,沒有其他的配置,都在這兒了。完成程式碼後,開啟兩個瀏覽器,可以看到兩個頁面可以實現即時通訊的功能。(如下圖效果!)

我這些內容也是看了好幾篇部落格,現在寫出來記在自己的小本本上,免得下次還得搜其他人的