rt-sim-training-client/src/utils/sock.js
2021-01-11 17:51:54 +08:00

168 lines
5.3 KiB
JavaScript

import { getToken } from '@/utils/auth';
import { checkLoginLine } from '@/api/login';
import { getBaseUrl } from '@/utils/baseUrl';
import { MessageBox } from 'element-ui';
import store from '@/store/index';
import Stomp from 'stompjs';
const isDev = process.env.NODE_ENV === 'development';
const isTest = process.env.NODE_ENV === 'test';
const websocketUrl = `${getBaseUrl()}/joylink-websocket?token=`;
const reconnectInterval = [1000, 3000, 5000, 10000, 30000, 60000];
var StompClient = function (headers) {
this.url = websocketUrl + getToken();
this.headers = headers || {};
this.subscribeMap = new Map(); // 已订阅,对象{dest:'', handler:function, sub: Object}
this.connect();
};
StompClient.prototype = {
websocket: null,
clientIns: null,
url: '',
status: false,
sockStatus: 0,
headers: {
// 'X-Token': getToken()
},
isPassived:true, // 是否被动断线重连
count: 0,
topic: '',
onmessage: null,
// 连接服务端
connect() {
// 向服务器发起websocket连接并发送CONNECT帧
this.websocket = new WebSocket(this.url.replace(/https/, 'wss').replace(/http/, 'ws'));
// 获取 STOMP 子协议的客户端对象
this.clientIns = Stomp.over(this.websocket);
this.closeStompDebug();
const that = this;
this.clientIns.connect({ 'X-Token': getToken() }, () => {
console.info('连接成功.');
that.count = 0;
that.status = true;
// 恢复订阅
that.subscribeMap.forEach((subscribe) => {
that.subscribe(subscribe.dest, subscribe.handler);
});
}, (e)=> {
console.log('socket连接错误:' + e);
this.status = false;
});
// sock断开回调
that.clientIns.ws.onclose = () => {
that.status = false;
console.info(`通信连接已断开!`);
checkLoginLine().then((resp) => {
if (resp.code == 200) {
that.count++;
that.reconnect(that.count);
}
}).catch((err) => {
that.logOut(err);
});
};
},
logOut(err) {
console.info(err);
// 退出登陆前断开连接
store.dispatch('disconnect').then(()=>{
MessageBox.confirm('你已被登出,请重新登录', '确定登出', {
confirmButtonText: '重新登录',
showCancelButton: false,
type: 'warning'
}).then(() => {
store.dispatch('FedLogOut').then(() => {
location.reload();// 为了重新实例化vue-router对象 避免bug
});
});
});
},
// 恢复链接
reconnect(count) {
console.info(`尝试第${count || 1}次连接.`);
// Message.warning(`正在尝试第${count || 1}次通讯连接。`);
const that = this;
if (this.clientIns) { // 初始化stomp和websocket
if (this.clientIns.connected) {
this.clientIns.disconnect();
}
this.websocket.close();
this.websocket = null;
this.clientIns = null;
}
setTimeout(() => {
that.connect();
}, reconnectInterval[that.count] || reconnectInterval[reconnectInterval.length - 1] );
},
closeStompDebug() {
if (this.clientIns) {
if (isDev || isTest) {
this.clientIns.debug = function (message) { console.debug(message); };
} else {
this.clientIns.debug = function (message) {};
}
}
},
// 订阅指定的topic
subscribe(topic, onmessage, headers) {
this.topic = topic;
this.onmessage = onmessage;
this.headers = headers;
if (!this.status) {
this.subscribeMap.set(topic, {dest: topic, handler: onmessage, sub: null});
} else {
const sub = this.clientIns.subscribe(topic, onmessage);
this.subscribeMap.set(topic, {dest: topic, handler: onmessage, sub: sub});
}
},
unsubscribe(topic) {
const subscription = this.subscribeMap.get(topic);
if (subscription && subscription.sub) {
subscription.sub.unsubscribe();
this.subscribeMap.delete(topic);
console.log('取消订阅:' + topic);
} else if (subscription) {
this.subscribeMap.delete(topic);
}
},
// 发送消息
send(url, msg) {
if (this.status) {
if (msg) {
msg = JSON.stringify(msg);
this.clientIns.send(url, {}, msg);
} else {
console.error('发送消息为空');
}
} else {
setTimeout(() => {
this.send(url, msg);
}, 300);
}
},
disconnect() {
if (this.clientIns) {
if (this.clientIns.connected) {
this.clientIns.disconnect();
}
this.isPassived = false;
this.websocket.close();
this.websocket = null;
this.clientIns = null;
}
this.status = false;
console.info('断开连接');
}
};
export default StompClient;