SpringBoot使用Socket向前端推送消息

個人資源與分享網站:http://xiaocaoshare.com/

1.對webSocket理解
WebSocket協議是基於TCP的一種新的網絡協議。它實現了瀏覽器與服務器全雙工(full-duplex)通信——允許服務器主動發送信息給客戶端。
2.使用webSocket好處
HTTP 協議有一個缺陷:通信只能由客戶端發起,HTTP 協議做不到服務器主動向客戶端推送信息。
3.SpringBoot2.0,在pom.xml加入以下依賴
<dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-websocket</artifactId>  
 </dependency> 
4.開啓webSocket支持
在SpringBoot配置類配置Bean
@Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
5.WebSocketServer
@ServerEndpoint("/websocket")
@Component
@Slf4j
public class WebSocketServer {

    // 靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
    private static int onlineCount = 0;
    // concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    // 與某個客戶端的連接會話,需要通過它來給客戶端發送數據
    private Session session;

    // 接收sid
    private String sid = "";

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

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

    /**
     * 收到客戶端消息後調用的方法
     *
     * @param message
     *            客戶端發送過來的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("來自客戶端的消息:" + message);
        // 羣發消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("發生錯誤");
        error.printStackTrace();
    }

    /**
     * 實現服務器主動推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 羣發自定義消息
     */
    public static void sendInfo(String message) throws IOException {

        for (WebSocketServer item : webSocketSet) {
            try {
                // 這裏可以設定只推送給這個sid的,爲null則全部推送

                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

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

}

6.消息推送
寫個控制器,調用WebSocketServer.sendInfo();
@RestController
public class SendMessageController {

    @RequestMapping("sendInfo")
    public String sendInfo(@RequestParam String msg) {
        try {
            WebSocketServer.sendInfo(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return "信息發送異常!";
        }
        return "發送成功~";
    }
}

7.頁面代碼
<!DOCTYPE HTML>
  <html>
  <head>
      <title>WebSocket</title>
  </head>
  
  <body>
  <div style="width: 800px;height: 100%; margin: 0px auto;">
      <span style="color: coral; font-size: 22px;"> Welcome WebSocket</span><br/><br/>
     <div id="message">
     </div>
 </div>
 </body>
 
 <script type="text/javascript">
     var websocket = null;
     //判斷當前瀏覽器是否支持WebSocket
     if('WebSocket' in window){
         websocket = new WebSocket("ws://localhost:8002/websocket");
     }else{
         alert('連接失敗!!')
     }
 
     //連接發生錯誤的回調方法
     websocket.onerror = function(){
         setMessageInnerHTML("error");
     };
 
     //連接成功建立的回調方法
     websocket.onopen = function(event){
         setMessageInnerHTML("webSocket 連接成功~");
     }
 
     //接收到消息的回調方法
     websocket.onmessage = function(event){
         setMessageInnerHTML(event.data);
     }
 
     //連接關閉的回調方法
     websocket.onclose = function(){
         setMessageInnerHTML("close");
     }
 
     //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,
     // 防止連接還沒斷開就關閉窗口,server端會拋異常。
     window.onbeforeunload = function(){
         websocket.close();
     }
 
     //將消息顯示在網頁上
     function setMessageInnerHTML(innerHTML){
         document.getElementById('message').innerHTML += innerHTML + '<br/>';
     }
 
     //關閉連接
     function closeWebSocket(){
        websocket.close();
     }
 
   </script>
 </html>

8.測試
1.建立2個連接,就是打開兩個窗口,訪問http://localhost:8002/websocket.html

2.後臺向前端推送消息
新打開一個窗口,訪問http://localhost:8002/sendInfo?msg=測試websocket

代碼:https://github.com/xiaoyirang/SpringBootDemo

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