前言
最近在做一個客戶端通信功能烙心,由于websocket可以進行雙向通信(服務器可以主動向客戶端推送信息村砂,客戶端也可以主動向服務器發(fā)送信息),因此選擇了vue-native-websocket
一、安裝插件vue-native-websocket
yarn add vue-native-websocket
# or
npm install vue-native-websocket --save
二、app.js 引入websocke插件
import websocket from 'vue-native-websocket';
Vue.use(websocket, 'ws://localhost:9090', {// 需要連接的服務器地址河劝,端打包后可以填地址(localhost:...),調(diào)試階段需填寫對應開發(fā)本地地址(同個局域網(wǎng),能ping通的地址)或部署的在線服務地址
reconnection: true, // (Boolean)是否自動重連矛紫,默認false
reconnectionAttempts: 5, // 重連次數(shù)
reconnectionDelay: 3000, // 再次重連等待時常(1000)
});
三赎瞎、app.vue 初始化websocket
methods: {
...mapMutations('common', ['setSocketMessage']),
// 初始化weosocket
initWebSocket() {
this.$socket.onopen = this.websocketonopen;//連接成功方法
this.$socket.onerror = this.websocketonerror;//報錯方法
this.$socket.onmessage = this.websocketonmessage;// 接收端返回或推送信息的方法
this.$socket.onclose = this.websocketclose;//關閉
},
// 鏈接ws服務器,e.target.readyState = 0/1/2/3 0 CONNECTING ,1 OPEN, 2 CLOSING, 3 CLOSED
websocketonopen(e) {
console.log('WebSocket連接成功,app.vue', e);
},
// 接收端發(fā)送過來的信息颊咬,整個項目接收信息的唯一入口
websocketonmessage(e) {
if (!e.data) {return;}
let res = JSON.parse(e.data);
if(res.error && res.error.code){//返回失敗信息
this.$message({
type: 'error',
message:getTipCode(Number(res.error.code)),//匹配失敗code的提示文案
});
}
//端返回成功信息
if (res.status == 200 && res.action) {
switch (res.action) {
case 'getClientInfo':
console.log("返回的客戶端信息"务甥,res.data)
break;
default:
this.setSocketMessage(e.data);//把信息存到vuex里面,再分發(fā)到對應頁面
break;
}
}
//端主動發(fā)起的
if (res.method) {
switch (res.method) {
case 'loginOut':
console.log("接收到消息喳篇,執(zhí)行退出登錄操作")
break;
case 'msgCenter':
console.log("接收到消息敞临,打開消息中心")
this.$router.push('/noticeCenter');
break;
default:
break;
}
}
}
}
四、vuex分發(fā)消息
state:{
websocketMessage: "",// 端返回的信息
socketTimestamp: new Date().getTime(),//時間戳去監(jiān)聽數(shù)據(jù)的改變
}麸澜,
mutations:{
//websocket
setSocketMessage(state, data) {//一旦獲取到端端返回的信息挺尿,就改變時間戳
state.socketTimestamp = new Date().getTime();
state.websocketMessage = data;
},
}
五、子頁面獲取websoket返回的信息(監(jiān)聽到了時間戳的改變)
watch: {
// 監(jiān)聽到端有返回信息
socketTimestamp(old, newVal) {
this.handleMessage(this.websocketMessage);
}
}炊邦,
methods: {
getCacheList(){
this.$socket.send(JSON.stringify({ //向端發(fā)送協(xié)議
method: 'searchCacheList',
keyWords: this.keyWords,
}));
},
handleMessage(res) {//處理接收到的信息
res = JSON.parse(res);
if (res.status == 200) {
switch (res.action) {
case 'searchCacheList'://獲取協(xié)議信息
this.cacheList = res.data ? res.data : [];
break;
default:
break;
}
}
}
}