vue实现websocket断线重连

下面有demo和注释

<template>
  <div>
    <button @click="sendDevName('xxxxxxxx')">发送</button>
    {{data}}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      data: null
    }
  },
  // html加载完成后执行initWebSocket()进行websocket初始化
  mounted () {
    this.initWebSocket()
  },
  // 离开该层时执行,划重点了!!!
  destroyed: function () {
    // 离开路由之后断开websocket连接
    this.websock.close()
  },
  methods: {
    // 初始化websocket
    initWebSocket () {
      const path = 'ws://xxx.xxx.xxx.xxx:端口号/xxxxx'// 后台给的websocket的ip地址
      this.websock = new WebSocket(path)
      this.websock.onmessage = this.websocketOnMessage
      this.websock.onopen = this.websocketOnOpen
      this.websock.onerror = this.websocketOnError
      this.websock.onclose = this.websocketClose
    },
    // 连接建立成功的信号
    websocketOnOpen () {
      console.log('初始化成功')// 连接成功后就可以在这里写一些回调函数了
    },
    // 连接建立失败重连
    websocketOnError () {
      // 如果报错的话,在这里就可以重新初始化websocket,这就是断线重连
      this.initWebSocket()
    },
    // 数据接收
    websocketOnMessage (e) {
      console.log(e)// e这个变量就是后台传回的数据,在这个函数里面可以进行处理传回的值
      this.data = e// 这边我绑定了一个data,data会在网页上显示后端传来的东西
    },
    // 数据发送
    websocketSend (Data) {
      this.websock.send(Data)// Data变量就是你想对后台说些啥,根据后端给你的接口文档传值进行交互
    },
    // 关闭的信号
    websocketClose () {
      console.log('断开连接')
    },
    // 传参给后端,这里对websocketSend又进行了一层封装,用不到的可以删除
    sendDevName (chooseDevice) {
      console.log(chooseDevice)
      this.websocketSend(chooseDevice)
    }
  }
}
</script>

普及一下websocket的状态

websocket的两个属性:readyState和bufferedAmount。
根据readyState属性可以判断webSocket的连接状态,该属性的值可以是下面几种:
0 :对应常量CONNECTING (numeric value 0),
正在建立连接连接,还没有完成。The connection has not yet been established.
1 :对应常量OPEN (numeric value 1),
连接成功建立,可以进行通信。The WebSocket connection is established and communication is possible.
2 :对应常量CLOSING (numeric value 2)
连接正在进行关闭握手,即将关闭。The connection is going through the closing handshake.
3 : 对应常量CLOSED (numeric value 3)
连接已经关闭或者根本没有建立。The connection has been closed or could not be opened.
例:
var socket = new WebSocket(url);
if(socket.readyState!=1){
alert(“未连接。”);
return;
}
根据bufferedAmount可以知道有多少字节的数据等待发送,若websocket已经调用了close方法则该属性将一直增长。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值