SpringBoot 整合 WebSocket

SpringBoot整合WebSocket

  1. 添加pom依賴

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
  2. 添加配置

    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }
  3. 編寫WebSocket映射類

    @ServerEndpoint(value = "/socket")
    @Controller
    public class WebSocketController implements Serializable {
        //靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
        private static int onlineCount = 0;
    
        //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
        private static CopyOnWriteArraySet<WebSocketController> webSocketSet = new CopyOnWriteArraySet<WebSocketController>();
    
        //與某個客戶端的連接會話,需要通過它來給客戶端發送數據
        private Session session;
    
        /**
         * 連接建立成功調用的方法*/
        @OnOpen
        public void onOpen(Session session) {
            System.out.println(session.getAsyncRemote());
            this.session = session;
            webSocketSet.add(this);     //加入set中
            addOnlineCount();           //在線數加1
            System.out.println("有新連接加入!當前在線人數爲" + getOnlineCount());
            sendMessage("wsyjlly");
        }
    
        /**
         * 連接關閉調用的方法
         */
        @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);
            //羣發消息
            sendInfo(session.getId());
        }
    
        /**
         * 發生錯誤時調用
         * @OnError
         **/
        public void onError(Session session, Throwable error) {
            System.out.println("發生錯誤");
            error.printStackTrace();
        }
    
    
        private void sendMessage(String message) {
            this.session.getAsyncRemote().sendText(message);
        }
    
    
        /**
         * 羣發自定義消息
         * */
        private static void sendInfo(String message){
            for (WebSocketController item : webSocketSet) {
                item.sendMessage(message);
            }
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount() {
            WebSocketController.onlineCount++;
        }
    
        public static synchronized void subOnlineCount() {
            WebSocketController.onlineCount--;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章