webSocket另一种封装

const WSS_URL = `ws://192.168.138.122:8078`

let Socket = ''
let msg = ''
let webSocketdata = ''
let setIntervalWesocketPush = null

export function webSocketdata(){
  return 
}

/**建立连接 */
export function createSocket(type) {
  switch (type) {
    case 'server':
      msg = '{action": "stat.server}'
      break;
    case 'nodes':
      msg = '{"action": "stat.nodes"}'
      break;
  }
  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已连接')
  }
}

/**打开WS之后发送心跳 */
export function onopenWS() {
  sendPing() //发送心跳
}

/**连接失败重连 */
export function onerrorWS() {
  clearInterval(setIntervalWesocketPush)
  console.log('尝试重连中')
  Socket.close()
  createSocket() //重连
}

/**接收数据统一处理 */
export function onmessageWS(e) {
  window.dispatchEvent(new CustomEvent('onmessageWS', {
    detail: {
      data: e
    }
  }))
  data = e.data;
}

/**发送数据
 * @param eventType
 */
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)
  }
}

/**关闭WS */
export function oncloseWS() {
  clearInterval(setIntervalWesocketPush)
  console.log('websocket已断开')
}

/**发送心跳 */
export function sendPing() {
  setIntervalWesocketPush = setInterval(() => {
    Socket.send(msg)
  }, 3000)
}

 

posted @ 2020-05-15 16:24  小萌豚  阅读(209)  评论(0编辑  收藏  举报