1、SSE(Server-sent Events)
SSE(Server-sent Events)是 WebSocket
的一种轻量代替方案,使用 HTTP 协议。 => Server-Sent Events 教程
2、stomp 介绍
3、MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议)
4、课外阅读:[WebSocket 是什么原理?为什么可以实现持久连接?
]( )
================================================================== import { EventLsbridge } from ‘@/common/eventLsbridge’ import { loadFromSession } from ‘@/common/session-storage’ import { Message } from ‘element-ui’ const timer = { reconnectObj: null, wsTimeoutObj: null, serverTimeoutObj: null, // 重连时间间隔(s) reconnectTime: 3 } const state = { ws: null, // 心跳时间(s) wsTimeout: 20, // 等待心跳响应时间(s),等待心跳的响应时间要大于心跳时间4s以上 waitHeartTime: 24 } const mutations = { set_reconnectObj: (state, val) => { state.reconnectObj = val }, } const actions = { // 心跳重置 wsHearReset({ dispatch }) { clearTimeout(timer.serverTimeoutObj) clearTimeout(timer.wsTimeoutObj) dispatch(‘wsHeartStart’) }, // 开启心跳 wsHeartStart({ state, dispatch }) { timer.wsTimeoutObj = setTimeout(() => { if(state.ws && state.ws.readyState == 1) { state.ws.send(‘’) } else { dispatch(‘handlerWSError’) } }, state.wsTimeout * 1000) timer.serverTimeoutObj = setTimeout(() => { console.log(‘接收心跳异常!’) dispatch(‘handlerWSError’) }, state.waitHeartTime * 1000) }, // 初始化ws连接 initWebsocket({ dispatch, state }) { if (state.ws) { return } else { return new Promise(resolve => { let url = ${process.env['VUE_APP_WEBSOCKET']}/websocket state.ws = new WebSocket(url) state.ws.addEventListener(‘open’, e => { console.log(‘长连接连接成功’) clearTimeout(timer.reconnectObj) dispatch(‘wsHeartStart’) }) state.ws.addEventListener(‘message’, e => { dispatch(‘wsHearReset’) dispatch(‘handlerWSMessage’, e) }) state.ws.addEventListener(‘close’, e => { console.log(‘ws close’) dispatch(‘handlerWSClose’, e) }) state.ws.addEventListener(‘error’, e => { console.log(‘ws error’) dispatch(‘handlerWSError’, e) }) }) } }, handlerSend({state}, id = -1) { if(!state.ws) { return } if(state.ws.readyState == 1) { state.ws.send( JSON.stringify({ id }) ) } }, handlerWSClose({ state }, e) { state.ws?.close() }, handlerWSError({state, dispatch}, e) { console.log(‘ws-error’) state.ws?.close() state.ws = null dispatch(‘reconnect’) }, reconnect({state, commit, dispatch}) { console.log(‘ws-重连’) clearTimeout(timer.wsTimeoutObj) clearTimeout(timer.serverTimeoutObj) clearTimeout(timer.reconnectObj) if (loadFromSession(‘userInfo’)?.userId) { Message.warning(‘网络出现异常,请检查网络后尝试刷新页面’) } timer.reconnectObj = window.setTimeout(() => { dispatch(‘initWebsocket’) timer.reconnectTime += 4 if(timer.reconnectTime > 60) { timer.reconnectTime = 20 } }, timer.reconnectTime * 1000) }, // ws回调 handlerWSMessage({state}, e) { let respData = {} try { respData = JSON.parse(e.data) } catch (e) { // not todo } if (respData?.data) { EventLsbridge.vueEmit(EventLsbridge.eventName.wsData, respData) } } } export default { namespaced: true, state, mutations, actions }