记录一个websocket使用过程

        记录一个 websocket 使用过程。需要解决的问题是:公司一个需求,需要导出二十万条左右的数据。首先,导出这么多数据,请求时间超长,导致用户可能觉得网络卡住,下载大小超大,大概计算了一下应该是在两三个G,这样下载时间也过长,而且 excel 也无法打开这么多数据

        解决办法(并不是特别好,应该分片请求,但是后端只给这么多技术支持,而且本垃圾也没有做过):使用 websocket 建立一个长链接,直接请求在浏览器上的资源,后端将 excel 文件直接放置在浏览器上,放置多个 excel 文件,这样就能间接实现文件分片。

        使用过程:

  created() {
    this.initWebSocket();
  },
  destroyed() {
    // 组件销毁时关闭
    this.websocketclose();
  },
  data() {
    return {
      websock: null,
    };
  },
  methods: {
    initWebSocket() {
      //初始化weosocket
      const wsuri = "ws://172.16:8099"; // 地址更改为需要的地址 : 端口号如果nginx 有做配置可以不加
      this.websock = new WebSocket(wsuri); // 创建
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      this.websocketsend();
    },
    websocketonerror() {
      //连接建立失败重连
      this.initWebSocket();
    },
    websocketonmessage(e) {
      //数据接收
      const redata = JSON.parse(e.data);
      let a = document.createElement("a");
      a.href = VUE_APP_BASE + redata.data;  // 此处使用公司阿里云服务
      a.click();
    },
    websocketsend() {
      //数据发送
      this.websock.send(data); // 此处添加需要发送的数据
    },
    websocketclose(e) {
      console.log(e, '建立失败')
    },
  },

猜你喜欢

转载自blog.csdn.net/z_langjitianya/article/details/131189894
今日推荐