zoukankan      html  css  js  c++  java
  • 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)
    }
  • 相关阅读:
    POJ NOI MATH-7650 不定方程求解
    POJ NOI MATH-7656 李白的酒
    POJ NOI MATH-7654 等差数列末项计算
    POJ NOI MATH-7827 质数的和与积
    POJ NOI MATH-7830 求小数的某一位
    POJ NOI MATH-7833 幂的末尾
    POJ NOI MATH-7829 神奇序列求和
    POJ NOI MATH-7826 分苹果
    UVALive5661 UVA668 ZOJ2037 Parliament
    POJ1032 Parliament
  • 原文地址:https://www.cnblogs.com/water-no-moon/p/12895665.html
Copyright © 2011-2022 走看看