Vue——封装使用websocket

4,591 阅读1分钟

一:定义websocket.js

export default {
  ws:{},
  setWs: function(newWs) {
    this.ws = newWs
  }
}

二:在main.js中引入

import websocket from './utils/websocket'
Vue.prototype.$websocket = websocket

三:在App.vue中启动

1.定义启动方法 localSocket

    localSocket() {
      let that = this;
      if ("WebSocket" in window) {
        console.log("您的浏览器支持 WebSocket!");
        that.ws = new WebSocket(`ws://后端地址`);
        that.$websocket.setWs(that.ws);
        that.ws.onopen = function() {
          console.log('开始连接')
          that.$websocket.ws.send('给后端必要的参数')
        };
        that.ws.onclose = function() {
          // 防链接超时,(websocket在一定时间内没有数据交互,就会断开),关闭后重启
          console.log("连接已关闭...");
          setTimeout(() => {
            that.localSocket();
          }, 2000);
        };
      } else {
        // 浏览器不支持 WebSocket
        console.log("您的浏览器不支持 WebSocket!");
      }
    }

2.在钩子函数中使用

  created() {
    //websocket
    this.localSocket()
  },

四.在别的页面中接受消息

    this.$websocket.ws.onmessage = function(res) {
       console.log("收到服务器内容", res);
     };