1. 程式人生 > >websocket+springboot+vue+element ui完成資料表格的實時資料

websocket+springboot+vue+element ui完成資料表格的實時資料

java部分:

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @description:TODO
 * @author:xing.Li
 * @date:2019/8/26 10:02
 */
@Component
@ServerEndpoint("/websocket/{code}")
//此註解相當於設定訪問URL
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="code")String code) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(code, session);
        Constants.WEBSOCKET = true;//定義常亮是否開啟websocket連線
        System.out.println("【websocket訊息】有新的連線,總數為:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        Constants.WEBSOCKET = false;
        System.out.println("【websocket訊息】連線斷開,總數為:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket訊息】收到客戶端訊息:"+message);
    }

    // 此為廣播訊息
    public void sendAllMessage(String message) {
        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket訊息】廣播訊息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此為單點訊息
    public void sendOneMessage(String code, String message) {
        Session session = sessionPool.get(code);
        /*在傳送資料之前先確認 session是否已經開啟 使用session.isOpen() 為true 則傳送訊息
        * 不然會報錯:The WebSocket session [0] has been closed and no method (apart from close()) may be called on a closed session */
        if (session != null && session.isOpen()) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @description:TODO
 * @author:xing.Li
 * @date:2019/8/25 17:44
 */
@Configuration
public class WebSocketConfig {
    /**
     * 注入ServerEndpointExporter,
     * 這個bean會自動註冊使用了@ServerEndpoint註解宣告的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

最終要的當然是jar包了

<!--websocket-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>1.5.3.RELEASE</version>
    <type>pom</type>
</dependency>

js部分:

data(){} 中

created() { // 頁面建立生命週期函式
    this.initWebSocket()
},
destroyed: function () { // 離開頁面生命週期函式
    this.websocketclose();
},

methods中

initWebSocket: function () {
    // WebSocket與普通的請求所用協議有所不同,ws等同於http,wss等同於https   key你自定義的key
    var host = window.location.host;
    this.websock = new WebSocket("ws://" + host + "/websocket/key");
    this.websock.onopen = this.websocketonopen;
    this.websock.onerror = this.websocketonerror;
    this.websock.onmessage = this.websocketonmessage;
    this.websock.onclose = this.websocketclose;
},
websocketonopen: function () {
    console.log("WebSocket連線成功");
    console.log("WebSocket正在傳送實時資料.......");
},
websocketonerror: function (e) {
    console.log("WebSocket連線發生錯誤");
},
websocketonmessage: function (e) {
       JSON.parse(e.data); //這個是收到後端主動推送的值
    }
},
websocketclose: function (e) {
    console.log("WebSocket連線斷開");
}

實現思路:通過websocket長連線從後端主動推送資料,利用vue的雙向繫結實現資料同步

注:因為資料的改變也會重新整理表格上覆選框的選中狀態,本人思路為,element ui中有選中複選框的值得集合,判斷複選框裡面有沒有值,有值的話就是在操作資料,這時停止websocket的連線,操作完成後,複選框值所在集合也就沒有值了,這時再開啟websocket連線,這樣也有問題,但是算是實現了吧。。。。

在此記錄方便以後觀看

當然上面的部分程式碼是忘記那位博主的了,時間太久找不到連結了,就