美文网首页
websocket使用

websocket使用

作者: 懒懒猫 | 来源:发表于2022-03-10 10:16 被阅读0次

    安装

    创建websocket文件index.vue

    <template>
      <div></div>
    </template>
    <script>
    export default {
      name: 'WebSocket',
      props: {
      
        }
      },
    
      data () {
        return {
          websock: null,
          webSockCheckInterval: null,
          websockIsDestroying: false,
          websockErrTimes: 0
        }
      },
     
      created () {
          // 打开websocket链接
          if (window.WebSocket) {
            this.initWebSocket()
          } else {
            this.$message.warning(
              '该浏览器不支持提醒。&lt;br/&gt;建议使用高版本的浏览器,&lt;br/&gt;如 IE10、火狐 、谷歌  、搜狗等'
            )
          }
        })
      },
    
      methods: {
     
        initWebSocket () {
          this.createWebSocket()
    
          // 如果服务端断开重连(保持长连接)
          this.webSockCheckInterval = window.setInterval(() => {
            if (!this.websockIsDestroying && this.websock.readyState === 3) {
              this.websockErrTimes = 0
              this.createWebSocket()
            }
          }, 60000)
        },
        // 创建WebSocket(初始化创建及断开重连)
        createWebSocket () {
    // 设置动态websocket Ip
          //   const sid = 'DDY'
          var urlPath = window.document.location.href // 浏览器显示地址 http://10.15.5.83:5555/ISV/demo.aspx?a=1&b=2
          var docPath = window.document.location.pathname // 文件在服务器相对地址 /ISV/demo.aspx
          var index = urlPath.indexOf(docPath)
          var serverPath = urlPath.substring(0, index)
    
          var result1 = serverPath.substring(serverPath.indexOf(':') + 1)
          var result2 = result1.substring(0, result1.indexOf(':'))
    
          // this.websock = new WebSocket('ws:' + result2 + ':8886')
          console.log('ws:' + result2 + ':8886')
          console.log(process.env.VUE_APP_API_WEBSOCKET_BASE_URL)
          this.websock = new WebSocket(process.env.VUE_APP_API_WEBSOCKET_BASE_URL)
          this.websock.onmessage = this.webSocketOnMessage
          this.websock.onopen = this.webSocketOnOpen
          this.websock.onerror = this.webSocketOnError
          this.websock.onclose = this.websocketOnCose
        },
        heartBeatReset () {
          this.heartBeatEnd()
          this.heartBeatStart()
        },
        heartBeatEnd () {
          clearTimeout(this.heartTimeOut)
        },
        heartBeatStart () {
          this.heartTimeOut = window.setTimeout(() => {
            var message = {
              cmd: 13,
              hbbyte: '-127'
            }
            this.webSocketSend(JSON.stringify(message))
          }, 1000)
        },
        // 释放WebSocket
        destroyWebSocket () {
          this.websockIsDestroying = true
          if (!!this.websock && this.websock.readyState === 1) {
            this.websock.close()
          }
          window.clearInterval(this.webSockCheckInterval)
          this.heartBeatEnd()
        },
        // 创建连接完成事件处理函数
        webSocketOnOpen (e) {
          const params = {
            userId: this.userInfo.userId,
            userName: this.userInfo.userName,
            userType: this.userInfo.userType,
            cmd: 5
          }
          this.webSocketSend(JSON.stringify(params))
    
          // 每隔一分钟登录一次
          setInterval(() => {
            const params = {
              userId: this.userInfo.userId,
              userName: this.userInfo.userName,
              userType: this.userInfo.userType,
              cmd: 5
            }
            this.webSocketSend(JSON.stringify(params))
          }, 60000)
    
          this.websockErrTimes = 0
          this.heartBeatReset()
        },
        // WebSocket异常事件处理函数
        webSocketOnError (e) {
          console.log(e, '链接出错了')
          window.setTimeout(() => {
            if (++this.websockErrTimes < 5 && !this.websockIsDestroying && this.websock.readyState === 3) {
              console.log('我重新连接了')
              // 失败重连
              this.createWebSocket()
            }
          }, 3000)
        },
        // 消息数据接收事件
        webSocketOnMessage (e) {
          this.heartBeatReset()
          try {
            var data = JSON.parse(e.data)
          } catch (err) {
            console.log(e.data)
          }
    
          // 登录成功后
          if (data.command === 6) {
            this.COMMAND_LOGIN_RESP()
          }
    
          // 管理员成功加入群组
          if (data.command === 9) {
          
          }
    
          if (data.command === 10) {
          }
    
          // 发送接收消息
          if (data.command === 11) {
           
          }
    
          // 发送成功
          if (data.command === 12) {
        
          }
          // 心跳
          if (data.command === 13) {
          }
        },
        // 关闭事件处理程序
        websocketOnCose (e) {
          // 关闭
          // console.log('close websocket', e);
        },
        // 数据发送
        webSocketSend (Data) {
          this.websock.send(Data)
        },
    
      destroyed () {
        console.log('退出')
        this.destroyWebSocket()
        removeOnlineUser(this.userInfo.userId, this.userInfo.userType).then(res => {})
      }
    }
    </script>
    
    

    在所需页面引用

    <WebSocket />
    import WebSocket from '@/components/WebSocket/index2' // 通信websocket
    components: {
    WebSocket // 通信websocket
    },

    相关文章

      网友评论

          本文标题:websocket使用

          本文链接:https://www.haomeiwen.com/subject/iynjlrtx.html