WebSocket 是 html5 開始提供的一種在單個 TCP 連接上進行全雙工通訊的協議。
WebSocket 使得客戶端和服務器之間的數據交換變得更加簡單,允許服務端主動向客戶端推送數據。在 WebSocket API 中,瀏覽器和服務器只需要完成一次握手,兩者之間就直接可以創建持久性的連接,並進行雙向數據傳輸。
這套代碼可以拿過去直接用 一些注意我會在下面代碼中加上注釋:
核心代碼
//這里需要引入vuex import store from './store'; let wsConnection = { $ws: null, lockReturn: false, timeout: 60 * 1000 * 5, timeoutObj: null, timeoutNum: null, serverTimeoutObj: null, //初始化webSocket長連接 initWebSocket: function () { let corpId = localStorage.getItem('corpId'); let name = localStorage.getItem('username'); this.$ws = new WebSocket(wsurl);//寫入地址 這里的地址可以在initWebSocket方法加入參數 this.$ws.onopen = this.wsOpen; this.$ws.onclose = this.wsClose; this.$ws.onmessage = this.wsMsg; this.$ws.onerror = this.wsError; }, //打開websocket wsOpen: function (e) { //開始websocket心跳 wsConnection.startWsHeartbeat(); console.log('ws success') }, wsClose: function (e) { console.log(e, 'ws close') }, wsMsg: function (msg) { //每次接收到服務端消息后 重置websocket心跳 wsConnection.resetHeartbeat(); //服務端發送來的消息存到vuex store.commit('web_socket_msg', msg) }, wsError: function (err) { console.log(err, 'ws error'); wsConnection.reconnect() }, //重啟websocket reconnect: function () { let _this = this; if (_this.lockReturn) { return; } _this.lockReturn = true; _this.timeoutNum && clearTimeout(_this.timeoutNum); _this.timeoutNum = setTimeout(function () { _this.initWebSocket(); _this.lockReturn = false; }, 3000); }, startWsHeartbeat: function () { let _this = this; _this.timeoutObj && clearTimeout(_this.timeoutObj); _this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj); _this.timeoutObj = setInterval(function () { //判斷websocket當前狀態 if (_this.$ws.readyState != 1) { _this.reconnect() } }, _this.timeout); }, //重置websocket心跳 resetHeartbeat: function () { let _this = this; clearTimeout(_this.timeoutObj); clearTimeout(_this.serverTimeoutObj); _this.startWsHeartbeat() } }; //拋出websocket對象 export default wsConnection
PPT模板下載大全https://www.wode007.com
websocket方法調用
//在main.js引入 import wsConnection from './vuex/wsStore' //掛載vue原型鏈 Vue.prototype.$setWs = wsConnection; //在使用地方調用 $this.$setWs.initWebSocket(); //在需要使用服務端推送過來的消息時 //在computed方法聲明 getWsMsg() { //在核心代碼接收到的服務端信息存儲到vuex的屬性 return this.$store.state.webSocketMsg } //在watch方法 監聽 getWsMsg getWsMsg: function (data, val) { console.log(data); //....... }