1. 程式人生 > >SpringBoot學習筆記02——SpringBoot專案WebSocket推送

SpringBoot學習筆記02——SpringBoot專案WebSocket推送

SpringBoot中建立WebSocket推送

使用SpringBoot建立WebSocket推送比較簡單,只需要以下三步即可。

1.建立一個配置類 WebSocketConfig

package com.adc.da.publish.websocket.config;

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

/**
 * websocket配置類
 *
 * @author: 劉朋
 * <br/>date: 2018-09-20
 */

@Configuration
public class WebSocketConfig {

    /**
     * 定義ServerEndpointExporter
     *
     * @param
     * @return
     * @author 劉朋
     * <br/>date 2018-09-20
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

2.建立一個WebSocket推送類

package com.adc.da.publish.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 單車監控websocket
 *
 * @author 劉朋
 * <br/>date 2018-09-20
 */

@ServerEndpoint("/testWebsocket")
@Component
public class MyWebSocket {

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

    //concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    //與某個客戶端的連線會話,需要通過它來給客戶端傳送資料
    private Session session;

    /**
     * 連線建立成功呼叫的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //線上數加1
        System.out.println("有新連線加入!當前線上人數為" + getOnlineCount());
        try {
            sendMessage("新人上限");
        } 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);
    }

    /**
     * 群發自定義訊息
     */
    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--;
    }

}

3.建立前端頁面

js中的埠號是本人自己定義的,可以隨意定義。

<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判斷當前瀏覽器是否支援WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8107/testWebsocket");
    }
    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");
    }

    //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,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>
</html>