Spring Boot 之Websocket 編程筆記

    有時候會用到向前端頁推送消息的情況,這時候就會用到WebSocket 編程了,

1.在pom.xml 中添加如下配置

  1.1核心是@ServerEndpoint這個註解。這個註解是Javaee標準裏的註解,tomcat7以上已經對其進行了實現,如果是用傳統方法使用tomcat發佈項目,只要在pom文件中引入javaee標準即可使用

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

  1.2 但使用springboot的內置tomcat時,就不需要引入javaee-api了,spring-boot已經包含了。使用springboot的websocket功能首先引入springboot組件。

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

          1.3. springboot的高級組件會自動引用基礎的組件,像spring-boot-starter-websocket就引入了spring-boot-starter-web和spring-boot-starter,所以不要重複引入。

2. 使用@ServerEndpoint 創立 websocket endpoint

  首先要注入ServerEndointExporTer,這個bean 會自動註冊使用了@ServerEndpoint 註解聲明的Websocket endpoint.要注意,如果使用獨立的servlet容器,而不是直接使用springBoot 內置容器,就不要注入ServerEndpointExporter,因爲它將由容器自己提供和管理。

配置類的代碼如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

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

3. 寫websocket 的具體實現類,代碼如下

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

@ServerEndpoint(value = "/websocket/{userCode}")
@Component
public class MyWebSocket {

	 //靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
    private static int onlineCount = 0;

    //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
   
    // 與某個客戶的鏈接會話,需要通過它來給客戶端發送數據
    
    private String currentUser;
    
    //與某個客戶端的連接會話,需要通過它來給客戶端發送數據
    private Session session;

    /**
     * 連接建立成功調用的方法*/
    @OnOpen
    public void onOpen(@PathParam("userCode") String userCode ,Session session) {
        this.session = session;
        this.currentUser = userCode;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在線數加1
        System.out.println("有新連接加入!當前在線人數爲" + getOnlineCount());
        try {
            sendMessage("ok");
        } catch (IOException e) {
            System.out.println("IO異常");
        }
    }

    /**
     * 連接關閉調用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
        subOnlineCount();           //在線數減1
        System.out.println("有一連接關閉!當前在線人數爲" + getOnlineCount());
    }

    /**
     * 收到客戶端消息後調用的方法
     *
     * @param message 客戶端發送過來的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("來自客戶端的消息:" + message);

        //羣發消息
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 發生錯誤時調用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("發生錯誤");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public static void sendMessageTo(String message,String userCode) throws IOException{
    	for(MyWebSocket item :webSocketSet){
    		if(item.currentUser.equals(userCode)){
    			item.session.getBasicRemote().sendText(message);
    		}
    	}
    }

    /**
     * 羣發自定義消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}

使用springboot的唯一區別是要@Component聲明下,而使用獨立容器是由容器自己管理websocket的,但在springboot中連容器都是spring管理的。

雖然@Component默認是單例模式的,但springboot還是會爲每個websocket連接初始化一個bean,所以可以用一個靜態set保存起來。

4.頁面調用簡單的方法類

<html>
    <head>
        <title> My Websocket</title>
    </head>
    <body>
        Wecome <br/>
        <input id="text"/><button onclick="send()">Send</button>
        <button onclick="closeWebSocket()">Close</button>
        <div id="message">

        </div>
        <script type="text/javascript">
        
         var websocket = null;
         //判斷當前瀏覽器是否支持webSocket
         if('WebSocket' in window){
           websocket = new WebSocket("ws://127.0.0.1:8988/websocket/1");
         }else{
             alert("NOt support websocket");
         }
         // 鏈接發生錯誤的回調方法
          websocket.onerror = function(){
              setMessageInnerHTML("error");
          }
         // 鏈接成功建立的回調方法
         websocket.onopen = function(event){
           setMessageInnerHTML("open");
         }
         // 接受到消息的回調方法
         websocket.onmessage = function(event){
          setMessageInnerHTML(event.data);
         }
         // 鏈接關閉的回調方法
        websocket.onclose = function(){
            setMessageInnerHTML("close");
        }

        //監聽窗口關閉事件,當窗口關閉時,主動關閉wesocket 鏈接,防止鏈接還沒斷開就關閉窗口,server端會拋異常。
        window.onbeforeunload = function(){
            websocket.close();
        }
        // 將消息顯示到網頁上
        function setMessageInnerHTML(innerHTML){
           document.getElementById('message').innerHTML += innerHTML+'<br/>';

        }
        
        // 關閉鏈接
        function closeWebSocket(){
            websocket.close();
        }
        
        //發送消息
        function send(){
           var message = document.getElementById("text").value;
       
            websocket.send(message);
        }
        </script>

    </body>
</html>

 4、總結

  springboot已經做了深度的集成和優化,要注意是否添加了不需要的依賴、配置或聲明。由於很多講解組件使用的文章是和spring集成的,會有一些配置,在使用springboot時,由於springboot已經有了自己的配置,再這些配置有可能導致各種各樣的異常。

 在webSocket 類中的參數不能引入實體類,這樣回報錯誤,具體爲啥報錯誤,我也沒有找到原因,回頭研究清楚了再補充上

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章