注意: 在app.vue onLaunch中調用webSocket這樣可以一進入系統就開啓webSocket。
步驟: 判斷是否已連接 --> 如未連接 打開連接(已連接就跳過) --> 打開成功監聽服務器返回的消息 -->前端用戶跟服務器進行綁定 --> 監聽到有新服務器消息,對服務器返回的新消息進行操作 --> 檢測心跳 --> 心跳已停止重新連接websocket
data() {
return {
timeout: 60000, // 1分鐘
timeoutObj: null,
}
},
onLaunch () {
// .判斷是否已連接
this.checkOpenSocket();
},
methods: {
// 判斷是否已連接
checkOpenSocket () {
let self = this;
uni.sendSocketMessage({
data: 'ping',
success: (res) => {
return;
},
fail: (err) => { // 未連接打開websocket連接
self.openConnection();
}
});
},
openConnection () { // 打開連接
uni.closeSocket(); // 確保已經關閉後再重新打開
uni.connectSocket({
url: this.$SOCKTURL,
method: 'POST',
success(res) {
console.log('連接成功 connectSocket=', res);
},
fail(err) {
console.log('連接失敗 connectSocket=', err);
}
});
uni.onSocketOpen((res) => {
console.log('連接成功', res);
});
this.onSocketMessage(2); // 打開成功監聽服務器返回的消息
},
// 打開成功監聽服務器返回的消息
onSocketMessage (type = 1) { // 消息
this.timeout = 60000;
this.timeoutObj = null;
uni.onSocketMessage((res) => {
let giveMsg = res.data;
// 後臺綁定client_id
if (giveMsg) {
let msg = JSON.parse(giveMsg);
if (msg.type === 'init' && type === 2) {
let clientId = msg.client_id;
let userId = uni.getStorageSync('userInfo');
let para = {client_id: clientId, userId : userId };
uni.request({ // 前端用戶跟服務器進行綁定
url: `htpp:/localhost:8080/v2/conference/user_binding'`,
data: para,
success: (res) => { // 綁定成功
if (res.statusCode === 200) {
this.reset(); // // 檢測心跳reset,防止長時間連接導致連接關閉
}
}
});
this.$API.get('conference/gateway_user_binding', para, 3).then(res => {
if (res.status === 1) { // 綁定成功
this.reset();
} else if (res.status === 0) {
console.log(res.errors[0]);
}
});
}
}
this.getSocketMsg(res.data); // 監聽到有新服務器消息
});
},
// 監聽到有新服務器消息
getSocketMsg (reData) { // 監聽到服務器消息
console.log('監聽到服務器消息 reData=', reData);
let info = JSON.parse(reData);
if (info.type === 'notice') {
console.log(info);
let options = {cover: false, title: info.time};
// #ifdef APP-PLUS
plus.push.createMessage(info.content, info, options); // 彈出到狀態欄中
// #endif
}
console.log('app onMessage=', reData)
},
// 檢測心跳reset
reset () {
clearInterval(this.timeoutObj);
this.start(); // 啓動心跳
},
// 啓動心跳 start
start () {
let self = this;
this.timeoutObj = setInterval(function(){
uni.sendSocketMessage({
data: 'ping',
success: (res) => {
console.log('連接中....');
},
fail: (err) => {
console.log('連接失敗重新連接....');
self.openConnection();
}
});
}, this.timeout);
}
},
}