websocket--信息推送和接收

websocket--信息推送和接收

场景
安全管理项目–数据大屏展播
目的
达到数据实时接收刷新页面
实现
websocket实时通讯(小白初次做,还望大神指点)
前期资料
假定我们创建了 Socket 对象: let Socket = new WebSocket(wsURL)

  • Socket属性: Socket.readyState
属性描述
Socket.readyState0-表示连接尚未建立
1-表示连接已建立,可以进行通信。
2-表示连接正在进行关闭。
3-表示连接已经关闭或者连接不能打开。
Socket.bufferedAmount只读属性 bufferedAmount 已被 send() 放入正在队列中等待传输,但是还没有发出的 UTF-8 文本字节数。
  • Socket事件
事件事件处理程序描述
openSocket.onopen连接建立时触发
messageSocket.onmessage客户端接收服务端数据时触发
errorSocket.onerror通信发生错误时触发
closeSocket.onclose连接关闭时触发
  • Socket方法
方法描述
Socket.send()使用连接发送数据
Socket.close()关闭连接

代码及注释

// mixins/websocket.js
export default {
  data () {
    return {
      message: 'hello',
      // websocket相关配置
      wsUrl: '', // 此处格式为地址加端口号,例: 'ws://119.*.*.*:8888'
      websocket: null, // 建立的连接
      lockReconnect: false, // 是否真正建立连接
      timeout: 30 * 1000, // 3o秒一次心跳
      timeoutObj: null, // 心跳倒计时
      //serverTimeoutObj: null, // 心跳倒计时-计时器-当时为了心跳超时直接关闭,不重连做的预留
      timeoutnum: null, // 断开 重连倒计时
      connectState: 0 // 连接状态
    }
  },
  mounted () {
  	let that = this
  	setTimeout(() => {
      that.initWebSocket()
    }, 300)
  },
  // 页面销毁,关闭websocket
  destroyed () {
    if (this.websocket && this.websocket.readyState === 1) {
      this.websocket.close()
    }
  },
  methods: {
  	// websocket通讯初始化
    initWebSocket () {
      let urli = this.wsUrl
      this.websocket = new WebSocket(urli)
      this.websocket.onopen = this.onopen
      this.websocket.onmessage = this.onmessage
      this.websocket.onclose = this.onclose
      this.websocket.onerror = this.onerror
    },
    // 重新链接ws
    reconnect () { // 重新连接
      var that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      // 没连接上会一直重连,设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(function () {
        // 新连接
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    },
    reset () { // 重置心跳
      var that = this
      // 清除时间
      clearTimeout(that.timeoutObj)
      clearTimeout(that.serverTimeoutObj)
      // 重启心跳
      that.start()
    },
    // 心跳检测
    start () { // 开启心跳
      var self = this
      self.timeoutObj && clearTimeout(self.timeoutObj)
      // self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
      self.timeoutObj = setTimeout(function () {
        // 这里发送一个心跳,后端收到后,返回一个心跳消息,
        if (self.websocket.readyState === 1) { // 如果连接正常
          self.websocket.send('heartCheck')
          self.reset()
        } else { // 否则重连
          self.reconnect()
        }
        // 以下代码多余
        // self.serverTimeoutObj = setTimeout(function () {
          // 超时关闭
          // self.websocket.close()
       // }, self.timeout)
      }, self.timeout)
    },
    // 开启ws
    onopen () {
      // 获取连接状态值
      this.connectState = this.websocket.readyState
      // 开启心跳
      this.start()
    },
    // ws发送数据
    sendData (data, type) {
      this.websocket.send('你好,服务器', data)
    },
    // ws获取数据
    onmessage (e) {
      console.log('服务器返回的数据', e.data)
      // 收到服务器信息,心跳重置
      this.reset()
    },
    // ws关闭
    onclose (e) {
      console.log('连接关闭')
      if (this.websocket.readyState === 1) {
        this.websocket.close('close')
      }
      // 重连
      this.reconnect()
    },
    // ws错误后重新连接
    onerror (e) {
      console.log('出现错误')
      // 重连
      this.reconnect()
    }
  }
}

---------------------------------------------------End------------------------------------------------

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值