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
| const WSS_URL = `wss://wss.xxxx.com/ws?appid=xxx` let Socket = '' let setIntervalWesocketPush = null
export function createSocket() { if (!Socket) { console.log('建立websocket连接') Socket = new WebSocket(WSS_URL) Socket.onopen = onopenWS Socket.onmessage = onmessageWS Socket.onerror = onerrorWS Socket.onclose = oncloseWS } else { console.log('websocket已连接') } }
export function onopenWS() { sendPing() }
export function onerrorWS() { clearInterval(setIntervalWesocketPush) Socket.close() createSocket() }
export function onmessageWS(e) { window.dispatchEvent(new CustomEvent('onmessageWS', { detail: { data: e } })) }
export function sendWSPush(eventTypeArr) { const obj = { appId: 'airShip', cover: 0, event: eventTypeArr } if (Socket !== null && Socket.readyState === 3) { Socket.close() createSocket() } else if (Socket.readyState === 1) { Socket.send(JSON.stringify(obj)) } else if (Socket.readyState === 0) { setTimeout(() => { Socket.send(JSON.stringify(obj)) }, 3000) } }
export function oncloseWS() { clearInterval(setIntervalWesocketPush) console.log('websocket已断开') }
export function sendPing() { Socket.send('ping') setIntervalWesocketPush = setInterval(() => { Socket.send('ping') }, 5000) }
|