Vue项目使用websocket

websocket 是长连接,受网络限制比较大

ajax轮询的原理是:让浏览器隔个几秒就发送一次请求,询问服务器是否有新信息。

用websocket主要原因是不需要用定时器几秒去请求一次接口查看进度

另外websocket地址用的是ws://wss://,应该是相当于http://https://

附代码:

<template>
  <div>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div style="margin-top:20px;width: 340px;">
        <a-progress :percent="progress" :status="status" />
      </div>

      <div style="margin-top:20px;">
        <a-button type="primary" @click="sendMessage()">发消息</a-button>
      </div>
    </a-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      disabled: false,
      status: 'active',
      progress: 0,
      count: 0,
      no: 0,
      path: 'ws://xxxxx', //接口地址
      socket: ''
    }
  },
  watch: {
    progress() {
      console.log(this.progress, '------')
    }
  },
  mounted() {
    this.init(this.path)
  },
  methods: {
    init(path) {
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持socket')
      } else {
        // 实例化socket
        this.socket = new WebSocket(path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    //实现化WebSocket对象
    //指定要连接的服务器地址与端口建立连接
    //注意ws、wss使用不同的端口。我使用自签名的证书测试,
    //无法使用wss,浏览器打开WebSocket时报错
    //ws对应http、wss对应https。
    //连接打开事件
    open: function() {
      console.log('Socket 已打开,socket连接成功')
    },
    //发生了错误事件
    error: function() {
      console.log('连接错误')
    },
    //收到消息事件
    getMessage: function(msg) {
      console.log(msg.data) //接收到的数据
      let obj = JSON.parse(msg.data)
      if (
        typeof obj == 'object' &&
        Object.prototype.toString.call(obj).toLowerCase() == '[object object]' &&
        !obj.length
      ) {
        // console.log('是JSON对象')
        this.no = obj.no
        this.count = obj.count
        this.progress = parseInt((this.no / this.count) * 100)
        this.status = 'active'
        if (this.progress == 100) {
          this.status = 'success'
          this.$message.success('成功!')
          setTimeout(() => {
            this.$router.go(0)
          }, 4000)
        }
      }
    },
    sendMessage: function() {
      this.disabled = !this.disabled
      this.socket.send(JSON.stringify(this.obj))
    },
    //连接关闭事件
    close: function() {
      console.log('socket已经关闭')
    }
  },
  destroyed() {
    console.log('离开')
    // 销毁监听
    this.socket.onclose = this.close()
  }
}
</script>
<style lang="less" scoped>
</style>

想要了解更多事件和属性等相关信息可以看这些

https://www.runoob.com/html/html5-websocket.html
http://www.ruanyifeng.com/blog/2017/05/websocket.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值