需要实现:有人触发门禁,就弹出消息信息
使用WebSocket 实现(由于项目重新发布会导致WebSocket断开连接,所以当断开时会定时请求连接WebSocket)
websocketInfo(){
var that = this;
var min = 100;
var max = 999;
var range = max-min;
var rande = Math.random();
var num = min + Math.round(range*rande);
if(typeof(WebSocket) == "undefined") {
console.log('您的浏览器不支持websocket');
}else{
that.socket = new WebSocket(that.wsUrl+new Date().getTime()+num);
console.log('连接状态:~~~'+that.socket.readyState);
//打开事件
if(that.timer.t10){
clearInterval(that.timer.t10);
}
if(that.timer.t11){
clearInterval(that.timer.t11);
}
that.socket.onopen = function() {
console.log("Socket 已打开");
};
//获得消息事件
that.socket.onmessage = function(msg) {
console.log(msg.data);
that.isstangerdetail = JSON.parse(msg.data);
if(that.isstangerdetail){
that.messageFlag?'':that.visitorDialog();
}
//发现消息进入开始处理前端触发逻辑
};
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
that.socket.onbeforeunload = function(err) {
that.websocket.close();
};
//关闭事件
that.socket.onclose = function(err) {
console.log('关闭');
console.log(err);
that.timer.t10 = setInterval(() =>{
clearInterval(that.timer.t11);
that.websocketInfo();
},3*1000)
};
//发生了错误事件
that.socket.onerror = function(err) {
console.log('错误');
console.log(err);
that.timer.t11 = setInterval(() =>{
clearInterval(that.timer.t10);
that.websocketInfo();
},3*1000)
//此时可以尝试刷新 页面
};
}
},