最近項(xiàng)目中有用到了webSocket,然后在收到消息之后需要在不同的頁(yè)面進(jìn)行處理。所有就需要在不同的頁(yè)面監(jiān)聽(tīng)并進(jìn)行對(duì)應(yīng)的消息處理。
首先,在app.vue中添加socket初始化,并設(shè)置發(fā)送消息,接收消息和心跳檢測(cè)的處理。
// App.vue
export default {
data() {
return {
// socket參數(shù)
socket: null,
timeout: 10 * 1000, // 45秒一次心跳
timeoutObj: null, // 心跳心跳倒計(jì)時(shí)
serverTimeoutObj: null, // 心跳倒計(jì)時(shí)
timeoutnum: null, // 斷開(kāi) 重連倒計(jì)時(shí)
lockReconnect: false, // 防止
websocket: null
};
},
mounted() {
this.initWebSocket(userId); // userId為socket鏈接的參數(shù)
},
methods:{
initWebSocket(supplierId) {
// WebSocket與普通的請(qǐng)求所用協(xié)議有所不同,ws等同于http,wss等同于https
let wsUrl = `wss://192.168.1.33/rest/supplier-api/wss/websocket/${userId}`;
this.websocket = new WebSocket(wsUrl);
this.websocket.onopen = this.websocketonopen;
this.websocket.onerror = this.websocketonerror;
this.websocket.onmessage = this.setOnmessageMessage;
this.websocket.onclose = this.websocketclose;
// 監(jiān)聽(tīng)窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒(méi)斷開(kāi)就關(guān)閉窗口,server端會(huì)拋異常。
// window.onbeforeunload = that.onbeforeunload
},
start() {
console.log('start');
//清除延時(shí)器
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(() => {
if (this.websocket && this.websocket.readyState == 1) {
this.websocket.send('heartBath');//發(fā)送消息,服務(wù)端返回信息,即表示連接良好,可以在socket的onmessage事件重置心跳機(jī)制函數(shù)
} else {
this.reconnect();
}
//定義一個(gè)延時(shí)器等待服務(wù)器響應(yīng),若超時(shí),則關(guān)閉連接,重新請(qǐng)求server建立socket連接
this.serverTimeoutObj = setTimeout(() => {
this.websocket.close();
}, this.timeout)
}, this.timeout)
},
reset() { // 重置心跳
// 清除時(shí)間
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
// 重啟心跳
this.start();
},
// 重新連接
reconnect() {
if (this.lockReconnect) return
this.lockReconnect = true;
//沒(méi)連接上會(huì)一直重連,設(shè)置延遲避免請(qǐng)求過(guò)多
this.timeoutnum && clearTimeout(this.timeoutnum);
this.timeoutnum = setTimeout(() => {
this.initWebSocket();
this.lockReconnect = false;
}, 5000)
},
async setOnmessageMessage(event) {
console.log(event.data, '獲得消息');
this.reset();
// 自定義全局監(jiān)聽(tīng)事件
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: event.data
}
}))
// //發(fā)現(xiàn)消息進(jìn)入 開(kāi)始處理前端觸發(fā)邏輯
// if (event.data === 'success' || event.data === 'heartBath') return
},
websocketonopen() {
//開(kāi)啟心跳
this.start();
console.log("WebSocket連接成功!!!"+new Date()+"----"+this.websocket.readyState);
},
websocketonerror(e) {
console.log("WebSocket連接發(fā)生錯(cuò)誤" + e);
},
websocketclose(e) {
this.websocket.close();
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
console.log("WebSocket連接關(guān)閉");
},
websocketsend(messsage) {
that.websocket.send(messsage)
},
closeWebSocket() { // 關(guān)閉websocket
that.websocket.close()
},
}
其中:在接收到消息之后需要自定一個(gè)監(jiān)聽(tīng)事件,來(lái)供頁(yè)面去監(jiān)聽(tīng)消息通知。
async setOnmessageMessage(event) {
console.log(event.data, '獲得消息');
this.reset();
// 自定義全局監(jiān)聽(tīng)事件
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: event.data
}
}))
// //發(fā)現(xiàn)消息進(jìn)入 開(kāi)始處理前端觸發(fā)邏輯
// if (event.data === 'success' || event.data === 'heartBath') return
},
最后在需要使用的頁(yè)面添加監(jiān)聽(tīng)事件文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-512458.html
mounted () {
// 添加socket通知監(jiān)聽(tīng)
window.addEventListener('onmessageWS', this.getSocketData)
},
methods: {
// 收到消息處理
getSocketData (res) {
if (res.detail.data === 'success' || res.detail.data === 'heartBath') return
// ...業(yè)務(wù)處理
},
}
至此,vue配置全局socket的需求就完成了。歡迎大佬們一起討論文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-512458.html
到了這里,關(guān)于vue設(shè)置全局webSocket,并在對(duì)應(yīng)頁(yè)面接受消息通知處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!