| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- export default {
- namespaced: true,
- state: {
- websock: {},
- url: '',
- lockReconnect: false, // 是否真正建立连接
- timeout: 30 * 1000, // 30秒一次心跳
- timeoutObj: {}, // 心跳心跳倒计时
- serverTimeoutObj: {}, // 心跳倒计时
- timeoutnum: {}, // 断开 重连倒计时
- message: {}
- },
- getters: {
- message (state) {
- return state.message
- }
- },
- mutations: {
- WEBSOCKET_INIT (state, url) {
- if (!state || !url) return
- let that = this
- state.websock = new WebSocket(url)
- state.url = url
- state.websock.onopen = () => {
- console.log('连接成功')
- // 发送心跳包
- that.commit('websocket/start')
- }
- state.websock.onmessage = (callBack) => {
- // 重置心跳
- // console.log('callBack = ' + callBack.data)
- that.commit('websocket/reset')
- if (callBack.data === 'heartCheck') {
- return
- }
- state.message = callBack.data
- }
- state.websock.onerror = () => { // e错误
- console.log('onerror')
- that.commit('websocket/reconnect')
- }
- state.websock.onclose = () => { // e关闭
- console.log('onclose')
- that.commit('websocket/reconnect')
- }
- },
- WEBSOCKET_SEND (state, message) {
- state.websock.send(message)
- },
- reconnect (state) { // 重新连接
- let that = this
- if (state.lockReconnect) {
- return
- }
- state.lockReconnect = true
- // 没连接上会一直重连,设置延迟避免请求过多
- state.timeoutnum && clearTimeout(state.timeoutnum)
- state.timeoutnum = setTimeout(() => {
- // 新连接
- that.commit('websocket/WEBSOCKET_INIT', state.url)
- state.lockReconnect = false
- }, 15000)
- },
- reset (state) { // 重置心跳
- // 清除时间
- clearTimeout(state.timeoutObj)
- clearTimeout(state.serverTimeoutObj)
- // 心跳
- this.commit('websocket/start')
- },
- start (state) {
- // 开启心跳
- let that = this
- state.timeoutObj && clearTimeout(state.timeoutObj)
- state.serverTimeoutObj && clearTimeout(state.serverTimeoutObj)
- state.timeoutObj = setTimeout(() => {
- // 这里发送一个心跳,后端收到后,返回一个心跳消息,
- // console.log(state.websock)
- if (state.websock.readyState === 1) { // 如果连接正常
- state.websock.send('heartCheck')
- } else { // 否则重连
- that.commit('websocket/reconnect')
- }
- state.serverTimeoutObj = setTimeout(() => {
- // 超时关闭
- state.websock.close()
- }, state.timeout)
- }, state.timeout)
- }
- },
- actions: {
- WEBSOCKET_INIT ({
- commit
- }, url) {
- commit('WEBSOCKET_INIT', url)
- },
- WEBSOCKET_SEND ({
- commit
- }, message) {
- commit('WEBSOCKET_SEND', message)
- }
- }
- }
|