1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| import { mapActions, mapState } from 'vuex'; export default { name: 'Websocket', data() { return { lockReconnect: false, socket: null, reconnectTimeout: null, timeout: 10 * 1000, timer: null, serverTimer: null }; }, computed: { ...mapState(['userInfo']), wsuri() { return `${process.env.VUE_APP_WEBSOCKET_URI}${this.userInfo.tenantId};${this.userInfo.userId}`; } }, async mounted() { await this.getUserInfo(); this.initWebSocket(); }, destroyed() { this.socket.close(); }, methods: { ...mapActions(['getUserInfo']), start(ws) { this.reset(); this.timer = setTimeout(() => { ws.send('ping'); this.serverTimer = setTimeout(() => { ws.close(); }, this.timeout); }, this.timeout); }, reset() { this.serverTimer && clearTimeout(this.serverTimer); this.timer && clearTimeout(this.timer); }, reconnect() { console.log('尝试重连'); if (this.lockReconnect) { return; } this.lockReconnect = true; this.reconnectTimeout && clearTimeout(this.reconnectTimeout); this.reconnectTimeout = setTimeout(() => { this.initWebSocket(); this.lockReconnect = false; }, 4 * 1000); }, initWebSocket() { try { if ('WebSocket' in window) { this.socket = new WebSocket(this.wsuri); } else { console.log('您的浏览器不支持websocket'); } this.socket.onopen = this.websocketOnOpen; this.socket.onerror = this.websocketOnError; this.socket.onmessage = this.websocketOnMessage; this.socket.onclose = this.websocketClose; } catch (e) { this.reconnect(); } }, websocketOnOpen() { console.log('WebSocket连接成功', this.socket.readyState); this.start(this.socket); this.websocketSend(); }, websocketOnError(e) { console.log('WebSocket连接发生错误', e); this.reconnect(); }, websocketOnMessage(e) { if (e.data === 'pong') { this.start(this.socket); } }, websocketClose(e) { console.log('connection closed (' + e.code + ')'); this.reconnect(); }, websocketSend() { this.socket.send('ping'); } } };
|